code_text
stringlengths 604
999k
| repo_name
stringlengths 4
100
| file_path
stringlengths 4
873
| language
stringclasses 23
values | license
stringclasses 15
values | size
int32 1.02k
999k
|
---|---|---|---|---|---|
var test = require('tap').test
var LRU = require('../')
test('forEach', function (t) {
var l = new LRU(5)
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
var i = 9
l.forEach(function (val, key, cache) {
t.equal(cache, l)
t.equal(key, i.toString())
t.equal(val, i.toString(2))
i -= 1
})
// get in order of most recently used
l.get(6)
l.get(8)
var order = [ 8, 6, 9, 7, 5 ]
var i = 0
l.forEach(function (val, key, cache) {
var j = order[i ++]
t.equal(cache, l)
t.equal(key, j.toString())
t.equal(val, j.toString(2))
})
t.equal(i, order.length);
t.end()
})
test('keys() and values()', function (t) {
var l = new LRU(5)
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
t.similar(l.keys(), ['9', '8', '7', '6', '5'])
t.similar(l.values(), ['1001', '1000', '111', '110', '101'])
// get in order of most recently used
l.get(6)
l.get(8)
t.similar(l.keys(), ['8', '6', '9', '7', '5'])
t.similar(l.values(), ['1000', '110', '1001', '111', '101'])
t.end()
})
test('all entries are iterated over', function(t) {
var l = new LRU(5)
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
var i = 0
l.forEach(function (val, key, cache) {
if (i > 0) {
cache.del(key)
}
i += 1
})
t.equal(i, 5)
t.equal(l.keys().length, 1)
t.end()
})
test('all stale entries are removed', function(t) {
var l = new LRU({ max: 5, maxAge: -5, stale: true })
for (var i = 0; i < 10; i ++) {
l.set(i.toString(), i.toString(2))
}
var i = 0
l.forEach(function () {
i += 1
})
t.equal(i, 5)
t.equal(l.keys().length, 0)
t.end()
})
test('expires', function (t) {
var l = new LRU({
max: 10,
maxAge: 50
})
for (var i = 0; i < 10; i++) {
l.set(i.toString(), i.toString(2), ((i % 2) ? 25 : undefined))
}
var i = 0
var order = [ 8, 6, 4, 2, 0 ]
setTimeout(function () {
l.forEach(function (val, key, cache) {
var j = order[i++]
t.equal(cache, l)
t.equal(key, j.toString())
t.equal(val, j.toString(2))
})
t.equal(i, order.length);
setTimeout(function () {
var count = 0;
l.forEach(function (val, key, cache) { count++; })
t.equal(0, count);
t.end()
}, 25)
}, 26)
})
| joaquimadraz/node_react_crash_course | 4_react_app/node_modules/gulp-browserify/node_modules/browserify/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js | JavaScript | mit | 2,347 |
/*! lazysizes - v2.0.3 */
!function(a,b){"use strict";function c(a){a.match(z)?this.urls[RegExp.$1]=t.map[RegExp.$2]||RegExp.$2:this.urls.include=t.map[a]||a}function d(a){var b,d,e;return a=a.trim(),a=t.map[a]||a,d=a.match(A),d?(e=RegExp.$1,b={condition:s.include.conditions[RegExp.$3]||s.customMedia[RegExp.$3]||RegExp.$2||null,name:RegExp.$3}):(e=a,b={condition:null,name:""}),b.urls={},(t.map[e]||e).split(y).forEach(c,b),!b.urls.include&&b.urls.amd&&(this.saved=!0,b.initial=this),b}function e(a){var b,c,e=a.getAttribute("data-include")||"",f=a.lazyInclude;return f&&f.str==e||(c={saved:!1,content:null},f={str:e,candidates:(t.map[e]||e).split(w).map(d,c)},!(b=f.candidates.length)||f.candidates[b-1].condition?(c.saved=!0,f.candidates.push({urls:{},condition:null,name:"initial",content:c})):c.saved&&1==f.candidates.length&&(c.saved=!1),f.initialContent=c,c.saved&&(c.content=a.innerHTML),a.lazyInclude=f,f.candidates.length>1?lazySizes.aC(a,"lazyconditionalinclude"):lazySizes.rC(a,"lazyconditionalinclude")),f}function f(b,c){var d=!c.condition;return c.condition&&(g(),v[c.name]?d=!0:a.matchMedia&&"string"==typeof c.condition?d=(matchMedia(c.condition)||{}).matches:"function"==typeof c.condition&&(d=c.condition(b,c))),d}function g(){var a;v||(u||(u=b.querySelector(t.contentElement)),u?(a=(E(u,":after").getPropertyValue("content")||"none").replace(B,""),v={},a&&(v[a]=1),a=(E(u,":before").getPropertyValue("content")||"none").replace(B,""),a&&(v[a]=1)):v={})}function h(a){var b,c,d=a.lazyInclude;if(d&&d.candidates)for(b=0;b<d.candidates.length&&(c=d.candidates[b],!f(a,c));b++);return c&&c!=d.current||(c=null),c}function i(a,b){var c=new XMLHttpRequest;c.addEventListener("readystatechange",function(){var a=this.DONE||4;this.readyState===a&&(b(c),c=null)},!1),c.open.apply(c,a.openArgs),c.setRequestHeader("X-Requested-With","XMLHttpRequest"),a.xhrModifier&&a.xhrModifier(c,elem,candidate),c.send(a.sendData)}function j(a,b){a=a.split("|,|"),require(a,b)}function k(a){if(!x[a]){var c=b.createElement("link"),d=b.getElementsByTagName("script")[0];c.rel="stylesheet",c.href=a,d.parentNode.insertBefore(c,d),x[a]=!0,x[c.href]=!0}}function l(a){a=a.split("|,|"),a.forEach(k)}function m(a){a&&"function"==typeof a.lazytransform&&a.lazytransform(this)}function n(a){a&&"function"==typeof a.lazyunload&&a.lazyunload(this)}function o(a){a&&"function"==typeof a.lazyload&&a.lazyload(this)}function p(b,c){var d,e,f,g=b.lazyInclude.current||null,h={candidate:c,openArgs:["GET",c.urls.include,!0],sendData:null,xhrModifier:null,content:c.content&&c.content.content||c.content,oldCandidate:g},k=lazySizes.fire(b,"lazyincludeload",h);return k.defaultPrevented?void F.d():(d=function(){var d,h=e.status,i=e.content||e.responseText,j=!(null!=i||!g||!g.urls.include),k={candidate:c,content:i,text:e.responseText||e.content,response:e.response,xml:e.responseXML,isSuccess:"status"in e?h>=200&&300>h||304===h:!0,oldCandidate:g,insert:!0,resetHTML:j},l={target:b,details:k,detail:k};c.modules=f,g&&g.modules&&(g.modules.forEach(n,l),g.modules=null,k.resetHTML&&null==k.content&&c.initial&&c.initial.saved&&(k.content=c.initial.content)),f.forEach(m,l),d=lazySizes.fire(b,"lazyincludeloaded",k),k.insert&&k.isSuccess&&!d.defaultPrevented&&null!=k.content&&k.content!=b.innerHTML&&(a.jQuery?jQuery(b).html(k.content):b.innerHTML=k.content),F.d(),f.forEach(o,l),setTimeout(function(){lazySizes.fire(b,"lazyincluded",k)}),e=null,f=null},b.lazyInclude.current=c,b.setAttribute("data-currentinclude",c.name),c.urls.css&&l(c.urls.css),null==h.content&&c.urls.include?i(h,function(a){e=a,f&&d()}):e=h,c.urls.amd||c.urls.module?(loadRequireImportCB=function(){f=Array.prototype.slice.call(arguments),e&&d()},c.urls.module&&a.System&&System["import"]?System["import"](c.urls.module).then(loadRequireImportCB):a.require&&j(c.urls.amd,loadRequireImportCB)):f=[],void(e&&f&&d()))}function q(a){var b,c=e(a);return c.candidates.length&&C.contains(a)?(b=h(a),b&&p(a,b),!0):void 0}function r(a){!a.defaultPrevented&&a.target.getAttribute("data-include")&&(F.q(a.target),a.detail.firesLoad=!0)}if(b.getElementsByClassName){var s,t,u,v,w=/\s*,+\s+/,x={},y=/\s+/,z=/^(amd|css|module)\:(.+)/i,A=/(.+)\s+(\(\s*(.+)\s*\))/,B=/['"]/g,C=b.documentElement,D=b.getElementsByClassName("lazyconditionalinclude"),E=function(b,c){var d=b.ownerDocument.defaultView;return d.opener||(d=a),d.getComputedStyle(b,c||null)||{getPropertyValue:function(){},isNull:!0}},F=function(){var a=2,b=3,c=a,d=0,e=0,f=[],g=function(){var a,b=function(){f.length&&(d=0,f.d())};return function(){clearTimeout(a),a=setTimeout(b,999)}}();return{q:function(a){var h=null==a.getAttribute("data-lazyqueue");h&&(e++,c=b),d>c?f[h?"unshift":"push"](a):q(a)&&(d++,g())},d:function(){if(d&&d--,e>0&&(e--,e||(c=a)),!(d>c)){for(;f.length;)if(q(f.shift())){d++;break}g()}}}}(),G=function(){var a,b=function(){for(var a=0,b=D.length;b>a;a++)!lazySizes.hC(D[a],s.lazyClass)&&h(D[a])&&lazySizes.aC(D[a],s.lazyClass)};return function(c){clearTimeout(a),v=null,a=setTimeout(b,"resize"==c.type?31:0)}}();s=a.lazySizes&&lazySizes.cfg||a.lazySizesConfig,s||(s={},a.lazySizesConfig=s),s.include||(s.include={}),t=s.include,t.contentElement||(t.contentElement="html"),t.conditions||(t.conditions={}),t.map||(t.map={}),addEventListener("lazybeforeunveil",r,!1),addEventListener("resize",G,!1),addEventListener("lazyrefreshincludes",G,!1)}}(window,document); | tholu/cdnjs | ajax/libs/lazysizes/2.0.4/plugins/include/ls.include.min.js | JavaScript | mit | 5,384 |
---
layout: default
---
<div class="teaserimage">
<div class="teaserimage-image" {% if site.cover %}style="background-image: url({{ site.cover }})"{% endif %}>
Teaser Image
</div>
</div>
<header class="blog-header">
{% if site.logo %}
<a class="blog-logo" href="{{site.url}}" style="background-image: url('{{ site.logo }}')">{{ site.title }}</a>
{% endif %}
<h1 class="blog-title">{{ site.title }}</h1>
<h2 class="blog-description">{{ site.description }}</h2>
<div class="custom-links">
{% for social in site.social %}
{% if social.url %}
<a class="icon-{{ social.icon }}" href="{{ social.url }}" {% if social.desc %} title="{{ social.desc }}"{% endif %}">
<i class="fa fa-{{ social.icon }}"></i>
</a>
·
{% endif %}
{% endfor %}
<a href="/about/">About</a>
</div>
</header>
<main class="content" role="main">
{% if site.tags.featured %}
<h5 class="index-headline featured"><span>Featured</span></h5>
<div class="container featured">
{% for post in site.tags.featured %}
<article class="post" itemscope itemtype="http://schema.org/BlogPosting" role="article">
<div class="article-item">
<header class="post-header">
<h2 class="post-title" itemprop="name"><a href="{{ post.url }}" itemprop="url">{{ post.title }}</a></h2>
</header>
<section class="post-excerpt" itemprop="description">
<p>{{ post.content | strip_html | truncatewords: 50 }}</p>
</section>
<div class="post-meta">
<time datetime="{{ post.date | date_to_long_string }}">{{ post.date | date_to_long_string }}</time>
<!-- <span class="post-tags-set">on {{#foreach tags}}<span class="post-tag-{{slug}}">{{#if @first}}{{else}}, {{/if}}<a href="/tag/{{slug}}">{{name}}</a></span>{{/foreach}}</span>-->
</div>
</div>
</article>
{% endfor %}
</div>
<h5 class="index-headline normal"><span>Regular</span></h5>
{% endif %}
<div class="cf frame">
{% for post in paginator.posts %}
<article class="post" itemscope itemtype="http://schema.org/BlogPosting" role="article">
<div class="article-item">
<header class="post-header">
<h2 class="post-title" itemprop="name"><a href="{{ post.url }}" itemprop="url">{{ post.title }}</a></h2>
</header>
<section class="post-excerpt" itemprop="description">
<p>{{ post.excerpt | strip_html | truncatewords: 50 }}</p>
</section>
<div class="post-meta">
<time datetime="{{ post.date | date_to_long_string }}">{{ post.date | date_to_long_string }}</time>
<!-- <span class="post-tags-set">on {{#foreach tags}}<span class="post-tag-{{slug}}">{{#if @first}}{{else}}, {{/if}}<a href="/tag/{{slug}}">{{name}}</a></span>{{/foreach}}</span>-->
</div>
</div>
</article>
{% endfor %}
</div>
<nav class="pagination" role="navigation">
{% if paginator.next_page %}
<a class="newer-posts" href="/page{{paginator.next_page}}">← Older posts</a>
{% endif %}
<span class="page-number">Page {{ paginator.page }} of {{ paginator.total_pages }}</span>
{% if paginator.previous_page %}
{% if paginator.page == 2 %}
<a class="older-posts" href="/">Newer posts →</a>
{% else %}
<a class="older-posts" href="/page{{paginator.previous_page}}">Newer posts →</a>
{% endif %}
{% endif %}
</nav>
<!-- {{!! After all the posts, we have the previous/next pagination links }}
{{pagination}} -->
</main>
| newagecrew/newageit | index.html | HTML | mit | 3,819 |
module.exports={title:"Qt",slug:"qt",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Qt</title><path d="M21.693 3.162H3.33L0 6.49v14.348h20.671L24 17.51V3.162zM12.785 18.4l-1.562.728-1.35-2.217c-.196.057-.499.09-.924.09-1.579 0-2.683-.425-3.305-1.276-.622-.85-.932-2.2-.932-4.033 0-1.84.319-3.206.949-4.098.63-.892 1.726-1.341 3.288-1.341 1.562 0 2.658.441 3.28 1.333.63.883.94 2.25.94 4.098 0 1.219-.13 2.2-.384 2.945-.261.752-.679 1.325-1.268 1.718zm4.736-1.587c-.858 0-1.447-.196-1.766-.59-.32-.392-.483-1.136-.483-2.232v-3.534H14.11V9.051h1.162V6.843h1.644V9.05h2.094v1.415h-2.094v3.346c0 .622.05 1.03.14 1.227.09.204.326.303.695.303l1.243-.05.073 1.326c-.67.13-1.186.196-1.546.196zm-8.58-9.08c-.95 0-1.604.311-1.963.94-.352.63-.532 1.629-.532 3.011 0 1.374.172 2.364.515 2.953.344.589 1.006.892 1.98.892.973 0 1.628-.295 1.971-.876.335-.58.507-1.57.507-2.953 0-1.39-.172-2.396-.523-3.026-.352-.63-1.006-.94-1.955-.94Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://qt-brandbook.webflow.io/design",hex:"41CD52",guidelines:"https://qt-brandbook.webflow.io/design",license:void 0}; | cdnjs/cdnjs | ajax/libs/simple-icons/5.0.0/qt.min.js | JavaScript | mit | 1,156 |
/*!
* autocomplete.js 0.21.8
* https://github.com/algolia/autocomplete.js
* Copyright 2016 Algolia, Inc. and other contributors; Licensed MIT
*/
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var angular = __webpack_require__(2);
// setup DOM element
var DOM = __webpack_require__(3);
DOM.element = angular.element;
// setup utils functions
var _ = __webpack_require__(4);
_.isArray = angular.isArray;
_.isFunction = angular.isFunction;
_.isObject = angular.isObject;
_.bind = angular.element.proxy;
_.each = angular.forEach;
_.map = angular.element.map;
_.mixin = angular.extend;
_.Event = angular.element.Event;
var EventBus = __webpack_require__(5);
var Typeahead = __webpack_require__(6);
angular.module('algolia.autocomplete', [])
.directive('autocomplete', ['$parse', '$injector', function($parse, $injector) {
// inject the sources in the algolia namespace if available
try {
$injector.get('algolia').sources = Typeahead.sources;
} catch (e) {
// not fatal
}
return {
restrict: 'AC', // Only apply on an attribute or class
scope: {
options: '&aaOptions',
datasets: '&aaDatasets'
},
link: function(scope, element, attrs) {
attrs = attrs; // no-unused-vars
scope.options = $parse(scope.options)(scope);
if (!scope.options) {
scope.options = {};
}
scope.datasets = $parse(scope.datasets)(scope);
if (scope.datasets && !angular.isArray(scope.datasets)) {
scope.datasets = [scope.datasets];
}
var eventBus = new EventBus({el: element});
var autocomplete = null;
// reinitialization watchers
scope.$watch('options', initialize);
if (angular.isArray(scope.datasets)) {
scope.$watchCollection('datasets', initialize);
} else {
scope.$watch('datasets', initialize);
}
// init function
function initialize() {
if (autocomplete) {
autocomplete.destroy();
}
autocomplete = new Typeahead({
input: element,
dropdownMenuContainer: scope.options.dropdownMenuContainer,
eventBus: eventBus,
hint: scope.options.hint,
minLength: scope.options.minLength,
autoselect: scope.options.autoselect,
openOnFocus: scope.options.openOnFocus,
templates: scope.options.templates,
debug: scope.options.debug,
cssClasses: scope.options.cssClasses,
datasets: scope.datasets,
keyboardShortcuts: scope.options.keyboardShortcuts
});
}
// Propagate the selected event
element.bind('autocomplete:selected', function(object, suggestion, dataset) {
scope.$emit('autocomplete:selected', suggestion, dataset);
});
// Propagate the autocompleted event
element.bind('autocomplete:autocompleted', function(object, suggestion, dataset) {
scope.$emit('autocomplete:autocompleted', suggestion, dataset);
});
// Propagate the opened event
element.bind('autocomplete:opened', function() {
scope.$emit('autocomplete:opened');
});
// Propagate the closed event
element.bind('autocomplete:closed', function() {
scope.$emit('autocomplete:closed');
});
// Propagate the cursorchanged event
element.bind('autocomplete:cursorchanged', function(event, suggestion, dataset) {
scope.$emit('autocomplete:cursorchanged', event, suggestion, dataset);
});
}
};
}]);
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = angular;
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
module.exports = {
element: null
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var DOM = __webpack_require__(3);
module.exports = {
// those methods are implemented differently
// depending on which build it is, using
// $... or angular... or Zepto... or require(...)
isArray: null,
isFunction: null,
isObject: null,
bind: null,
each: null,
map: null,
mixin: null,
isMsie: function() {
// from https://github.com/ded/bowser/blob/master/bowser.js
return (/(msie|trident)/i).test(navigator.userAgent) ?
navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
},
// http://stackoverflow.com/a/6969486
escapeRegExChars: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
},
isNumber: function(obj) { return typeof obj === 'number'; },
toStr: function toStr(s) {
return s === undefined || s === null ? '' : s + '';
},
cloneDeep: function cloneDeep(obj) {
var clone = this.mixin({}, obj);
var self = this;
this.each(clone, function(value, key) {
if (value) {
if (self.isArray(value)) {
clone[key] = [].concat(value);
} else if (self.isObject(value)) {
clone[key] = self.cloneDeep(value);
}
}
});
return clone;
},
error: function(msg) {
throw new Error(msg);
},
every: function(obj, test) {
var result = true;
if (!obj) {
return result;
}
this.each(obj, function(val, key) {
result = test.call(null, val, key, obj);
if (!result) {
return false;
}
});
return !!result;
},
any: function(obj, test) {
var found = false;
if (!obj) {
return found;
}
this.each(obj, function(val, key) {
if (test.call(null, val, key, obj)) {
found = true;
return false;
}
});
return found;
},
getUniqueId: (function() {
var counter = 0;
return function() { return counter++; };
})(),
templatify: function templatify(obj) {
if (this.isFunction(obj)) {
return obj;
}
var $template = DOM.element(obj);
if ($template.prop('tagName') === 'SCRIPT') {
return function template() { return $template.text(); };
}
return function template() { return String(obj); };
},
defer: function(fn) { setTimeout(fn, 0); },
noop: function() {},
className: function(prefix, clazz, skipDot) {
return (skipDot ? '' : '.') + prefix + '-' + clazz;
}
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var namespace = 'autocomplete:';
var _ = __webpack_require__(4);
var DOM = __webpack_require__(3);
// constructor
// -----------
function EventBus(o) {
if (!o || !o.el) {
_.error('EventBus initialized without el');
}
this.$el = DOM.element(o.el);
}
// instance methods
// ----------------
_.mixin(EventBus.prototype, {
// ### public
trigger: function(type) {
var args = [].slice.call(arguments, 1);
var event = _.Event(namespace + type);
this.$el.trigger(event, args);
return event;
}
});
module.exports = EventBus;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var attrsKey = 'aaAttrs';
var _ = __webpack_require__(4);
var DOM = __webpack_require__(3);
var EventBus = __webpack_require__(5);
var Input = __webpack_require__(7);
var Dropdown = __webpack_require__(11);
var html = __webpack_require__(13);
var css = __webpack_require__(14);
// constructor
// -----------
// THOUGHT: what if datasets could dynamically be added/removed?
function Typeahead(o) {
var $menu;
var $input;
var $hint;
o = o || {};
if (!o.input) {
_.error('missing input');
}
this.isActivated = false;
this.debug = !!o.debug;
this.autoselect = !!o.autoselect;
this.openOnFocus = !!o.openOnFocus;
this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
this.cssClasses = o.cssClasses = _.mixin({}, css.defaultClasses, o.cssClasses || {});
this.$node = buildDom(o);
$menu = this.$node.find(_.className(this.cssClasses.prefix, this.cssClasses.dropdownMenu));
$input = this.$node.find(_.className(this.cssClasses.prefix, this.cssClasses.input));
$hint = this.$node.find(_.className(this.cssClasses.prefix, this.cssClasses.hint));
if (o.dropdownMenuContainer) {
DOM.element(o.dropdownMenuContainer)
.css('position', 'relative') // ensure the container has a relative position
.append($menu.css('top', '0')); // override the top: 100%
}
// #705: if there's scrollable overflow, ie doesn't support
// blur cancellations when the scrollbar is clicked
//
// #351: preventDefault won't cancel blurs in ie <= 8
$input.on('blur.aa', function($e) {
var active = document.activeElement;
if (_.isMsie() && ($menu.is(active) || $menu.has(active).length > 0)) {
$e.preventDefault();
// stop immediate in order to prevent Input#_onBlur from
// getting exectued
$e.stopImmediatePropagation();
_.defer(function() { $input.focus(); });
}
});
// #351: prevents input blur due to clicks within dropdown menu
$menu.on('mousedown.aa', function($e) { $e.preventDefault(); });
this.eventBus = o.eventBus || new EventBus({el: $input});
this.dropdown = new Typeahead.Dropdown({menu: $menu, datasets: o.datasets, templates: o.templates, cssClasses: this.cssClasses, minLength: this.minLength})
.onSync('suggestionClicked', this._onSuggestionClicked, this)
.onSync('cursorMoved', this._onCursorMoved, this)
.onSync('cursorRemoved', this._onCursorRemoved, this)
.onSync('opened', this._onOpened, this)
.onSync('closed', this._onClosed, this)
.onSync('shown', this._onShown, this)
.onSync('empty', this._onEmpty, this)
.onAsync('datasetRendered', this._onDatasetRendered, this);
this.input = new Typeahead.Input({input: $input, hint: $hint})
.onSync('focused', this._onFocused, this)
.onSync('blurred', this._onBlurred, this)
.onSync('enterKeyed', this._onEnterKeyed, this)
.onSync('tabKeyed', this._onTabKeyed, this)
.onSync('escKeyed', this._onEscKeyed, this)
.onSync('upKeyed', this._onUpKeyed, this)
.onSync('downKeyed', this._onDownKeyed, this)
.onSync('leftKeyed', this._onLeftKeyed, this)
.onSync('rightKeyed', this._onRightKeyed, this)
.onSync('queryChanged', this._onQueryChanged, this)
.onSync('whitespaceChanged', this._onWhitespaceChanged, this);
this._bindKeyboardShortcuts($input, o);
this._setLanguageDirection();
}
// instance methods
// ----------------
_.mixin(Typeahead.prototype, {
// ### private
_bindKeyboardShortcuts: function($input, options) {
if (!options.keyboardShortcuts) {
return;
}
var keyboardShortcuts = [];
_.each(options.keyboardShortcuts, function(key) {
if (typeof key === 'string') {
key = key.toUpperCase().charCodeAt(0);
}
keyboardShortcuts.push(key);
});
DOM.element(document).keydown(function(event) {
var elt = (event.target || event.srcElement);
var tagName = elt.tagName;
if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') {
// already in an input
return;
}
var which = event.which || event.keyCode;
if (keyboardShortcuts.indexOf(which) === -1) {
// not the right shortcut
return;
}
$input.focus();
event.stopPropagation();
event.preventDefault();
});
},
_onSuggestionClicked: function onSuggestionClicked(type, $el) {
var datum;
if (datum = this.dropdown.getDatumForSuggestion($el)) {
this._select(datum);
}
},
_onCursorMoved: function onCursorMoved(event, updateInput) {
var datum = this.dropdown.getDatumForCursor();
if (datum) {
if (updateInput) {
this.input.setInputValue(datum.value, true);
}
this.eventBus.trigger('cursorchanged', datum.raw, datum.datasetName);
}
},
_onCursorRemoved: function onCursorRemoved() {
this.input.resetInputValue();
this._updateHint();
},
_onDatasetRendered: function onDatasetRendered() {
this._updateHint();
this.eventBus.trigger('updated');
},
_onOpened: function onOpened() {
this._updateHint();
this.eventBus.trigger('opened');
},
_onEmpty: function onEmpty() {
this.eventBus.trigger('empty');
},
_onShown: function onShown() {
this.eventBus.trigger('shown');
if (this.autoselect) {
this.dropdown.cursorTopSuggestion();
}
},
_onClosed: function onClosed() {
this.input.clearHint();
this.eventBus.trigger('closed');
},
_onFocused: function onFocused() {
this.isActivated = true;
if (this.openOnFocus) {
var query = this.input.getQuery();
if (query.length >= this.minLength) {
this.dropdown.update(query);
} else {
this.dropdown.empty();
}
this.dropdown.open();
}
},
_onBlurred: function onBlurred() {
if (!this.debug) {
this.isActivated = false;
this.dropdown.empty();
this.dropdown.close();
}
},
_onEnterKeyed: function onEnterKeyed(type, $e) {
var cursorDatum;
var topSuggestionDatum;
cursorDatum = this.dropdown.getDatumForCursor();
topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
if (cursorDatum) {
this._select(cursorDatum);
$e.preventDefault();
} else if (this.autoselect && topSuggestionDatum) {
this._select(topSuggestionDatum);
$e.preventDefault();
}
},
_onTabKeyed: function onTabKeyed(type, $e) {
var datum;
if (datum = this.dropdown.getDatumForCursor()) {
this._select(datum);
$e.preventDefault();
} else {
this._autocomplete(true);
}
},
_onEscKeyed: function onEscKeyed() {
this.dropdown.close();
this.input.resetInputValue();
},
_onUpKeyed: function onUpKeyed() {
var query = this.input.getQuery();
if (this.dropdown.isEmpty && query.length >= this.minLength) {
this.dropdown.update(query);
} else {
this.dropdown.moveCursorUp();
}
this.dropdown.open();
},
_onDownKeyed: function onDownKeyed() {
var query = this.input.getQuery();
if (this.dropdown.isEmpty && query.length >= this.minLength) {
this.dropdown.update(query);
} else {
this.dropdown.moveCursorDown();
}
this.dropdown.open();
},
_onLeftKeyed: function onLeftKeyed() {
if (this.dir === 'rtl') {
this._autocomplete();
}
},
_onRightKeyed: function onRightKeyed() {
if (this.dir === 'ltr') {
this._autocomplete();
}
},
_onQueryChanged: function onQueryChanged(e, query) {
this.input.clearHintIfInvalid();
if (query.length >= this.minLength) {
this.dropdown.update(query);
} else {
this.dropdown.empty();
}
this.dropdown.open();
this._setLanguageDirection();
},
_onWhitespaceChanged: function onWhitespaceChanged() {
this._updateHint();
this.dropdown.open();
},
_setLanguageDirection: function setLanguageDirection() {
var dir = this.input.getLanguageDirection();
if (this.dir !== dir) {
this.dir = dir;
this.$node.css('direction', dir);
this.dropdown.setLanguageDirection(dir);
}
},
_updateHint: function updateHint() {
var datum;
var val;
var query;
var escapedQuery;
var frontMatchRegEx;
var match;
datum = this.dropdown.getDatumForTopSuggestion();
if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
val = this.input.getInputValue();
query = Input.normalizeQuery(val);
escapedQuery = _.escapeRegExChars(query);
// match input value, then capture trailing text
frontMatchRegEx = new RegExp('^(?:' + escapedQuery + ')(.+$)', 'i');
match = frontMatchRegEx.exec(datum.value);
// clear hint if there's no trailing text
if (match) {
this.input.setHint(val + match[1]);
} else {
this.input.clearHint();
}
} else {
this.input.clearHint();
}
},
_autocomplete: function autocomplete(laxCursor) {
var hint;
var query;
var isCursorAtEnd;
var datum;
hint = this.input.getHint();
query = this.input.getQuery();
isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
if (hint && query !== hint && isCursorAtEnd) {
datum = this.dropdown.getDatumForTopSuggestion();
if (datum) {
this.input.setInputValue(datum.value);
}
this.eventBus.trigger('autocompleted', datum.raw, datum.datasetName);
}
},
_select: function select(datum) {
if (typeof datum.value !== 'undefined') {
this.input.setQuery(datum.value);
}
this.input.setInputValue(datum.value, true);
this._setLanguageDirection();
var event = this.eventBus.trigger('selected', datum.raw, datum.datasetName);
if (event.isDefaultPrevented() === false) {
this.dropdown.close();
// #118: allow click event to bubble up to the body before removing
// the suggestions otherwise we break event delegation
_.defer(_.bind(this.dropdown.empty, this.dropdown));
}
},
// ### public
open: function open() {
// if the menu is not activated yet, we need to update
// the underlying dropdown menu to trigger the search
// otherwise we're not gonna see anything
if (!this.isActivated) {
var query = this.input.getInputValue();
if (query.length >= this.minLength) {
this.dropdown.update(query);
} else {
this.dropdown.empty();
}
}
this.dropdown.open();
},
close: function close() {
this.dropdown.close();
},
setVal: function setVal(val) {
// expect val to be a string, so be safe, and coerce
val = _.toStr(val);
if (this.isActivated) {
this.input.setInputValue(val);
} else {
this.input.setQuery(val);
this.input.setInputValue(val, true);
}
this._setLanguageDirection();
},
getVal: function getVal() {
return this.input.getQuery();
},
destroy: function destroy() {
this.input.destroy();
this.dropdown.destroy();
destroyDomStructure(this.$node, this.cssClasses);
this.$node = null;
}
});
function buildDom(options) {
var $input;
var $wrapper;
var $dropdown;
var $hint;
$input = DOM.element(options.input);
$wrapper = DOM.element(html.wrapper.replace('%ROOT%', options.cssClasses.root)).css(css.wrapper);
// override the display property with the table-cell value
// if the parent element is a table and the original input was a block
// -> https://github.com/algolia/autocomplete.js/issues/16
if ($input.css('display') === 'block' && $input.parent().css('display') === 'table') {
$wrapper.css('display', 'table-cell');
}
var dropdownHtml = html.dropdown.
replace('%PREFIX%', options.cssClasses.prefix).
replace('%DROPDOWN_MENU%', options.cssClasses.dropdownMenu);
$dropdown = DOM.element(dropdownHtml).css(css.dropdown);
if (options.templates && options.templates.dropdownMenu) {
$dropdown.html(_.templatify(options.templates.dropdownMenu)());
}
$hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
$hint
.val('')
.addClass(_.className(options.cssClasses.prefix, options.cssClasses.hint, true))
.removeAttr('id name placeholder required')
.prop('readonly', true)
.attr({autocomplete: 'off', spellcheck: 'false', tabindex: -1});
if ($hint.removeData) {
$hint.removeData();
}
// store the original values of the attrs that get modified
// so modifications can be reverted on destroy
$input.data(attrsKey, {
dir: $input.attr('dir'),
autocomplete: $input.attr('autocomplete'),
spellcheck: $input.attr('spellcheck'),
style: $input.attr('style')
});
$input
.addClass(_.className(options.cssClasses.prefix, options.cssClasses.input, true))
.attr({autocomplete: 'off', spellcheck: false})
.css(options.hint ? css.input : css.inputWithNoHint);
// ie7 does not like it when dir is set to auto
try {
if (!$input.attr('dir')) {
$input.attr('dir', 'auto');
}
} catch (e) {
// ignore
}
return $input
.wrap($wrapper)
.parent()
.prepend(options.hint ? $hint : null)
.append($dropdown);
}
function getBackgroundStyles($el) {
return {
backgroundAttachment: $el.css('background-attachment'),
backgroundClip: $el.css('background-clip'),
backgroundColor: $el.css('background-color'),
backgroundImage: $el.css('background-image'),
backgroundOrigin: $el.css('background-origin'),
backgroundPosition: $el.css('background-position'),
backgroundRepeat: $el.css('background-repeat'),
backgroundSize: $el.css('background-size')
};
}
function destroyDomStructure($node, cssClasses) {
var $input = $node.find(_.className(cssClasses.prefix, cssClasses.input));
// need to remove attrs that weren't previously defined and
// revert attrs that originally had a value
_.each($input.data(attrsKey), function(val, key) {
if (val === undefined) {
$input.removeAttr(key);
} else {
$input.attr(key, val);
}
});
$input
.detach()
.removeClass(_.className(cssClasses.prefix, cssClasses.input, true))
.insertAfter($node);
if ($input.removeData) {
$input.removeData(attrsKey);
}
$node.remove();
}
Typeahead.Dropdown = Dropdown;
Typeahead.Input = Input;
Typeahead.sources = __webpack_require__(15);
module.exports = Typeahead;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var specialKeyCodeMap;
specialKeyCodeMap = {
9: 'tab',
27: 'esc',
37: 'left',
39: 'right',
13: 'enter',
38: 'up',
40: 'down'
};
var _ = __webpack_require__(4);
var DOM = __webpack_require__(3);
var EventEmitter = __webpack_require__(8);
// constructor
// -----------
function Input(o) {
var that = this;
var onBlur;
var onFocus;
var onKeydown;
var onInput;
o = o || {};
if (!o.input) {
_.error('input is missing');
}
// bound functions
onBlur = _.bind(this._onBlur, this);
onFocus = _.bind(this._onFocus, this);
onKeydown = _.bind(this._onKeydown, this);
onInput = _.bind(this._onInput, this);
this.$hint = DOM.element(o.hint);
this.$input = DOM.element(o.input)
.on('blur.aa', onBlur)
.on('focus.aa', onFocus)
.on('keydown.aa', onKeydown);
// if no hint, noop all the hint related functions
if (this.$hint.length === 0) {
this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
}
// ie7 and ie8 don't support the input event
// ie9 doesn't fire the input event when characters are removed
// not sure if ie10 is compatible
if (!_.isMsie()) {
this.$input.on('input.aa', onInput);
} else {
this.$input.on('keydown.aa keypress.aa cut.aa paste.aa', function($e) {
// if a special key triggered this, ignore it
if (specialKeyCodeMap[$e.which || $e.keyCode]) {
return;
}
// give the browser a chance to update the value of the input
// before checking to see if the query changed
_.defer(_.bind(that._onInput, that, $e));
});
}
// the query defaults to whatever the value of the input is
// on initialization, it'll most likely be an empty string
this.query = this.$input.val();
// helps with calculating the width of the input's value
this.$overflowHelper = buildOverflowHelper(this.$input);
}
// static methods
// --------------
Input.normalizeQuery = function(str) {
// strips leading whitespace and condenses all whitespace
return (str || '').replace(/^\s*/g, '').replace(/\s{2,}/g, ' ');
};
// instance methods
// ----------------
_.mixin(Input.prototype, EventEmitter, {
// ### private
_onBlur: function onBlur() {
this.resetInputValue();
this.trigger('blurred');
},
_onFocus: function onFocus() {
this.trigger('focused');
},
_onKeydown: function onKeydown($e) {
// which is normalized and consistent (but not for ie)
var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
this._managePreventDefault(keyName, $e);
if (keyName && this._shouldTrigger(keyName, $e)) {
this.trigger(keyName + 'Keyed', $e);
}
},
_onInput: function onInput() {
this._checkInputValue();
},
_managePreventDefault: function managePreventDefault(keyName, $e) {
var preventDefault;
var hintValue;
var inputValue;
switch (keyName) {
case 'tab':
hintValue = this.getHint();
inputValue = this.getInputValue();
preventDefault = hintValue &&
hintValue !== inputValue &&
!withModifier($e);
break;
case 'up':
case 'down':
preventDefault = !withModifier($e);
break;
default:
preventDefault = false;
}
if (preventDefault) {
$e.preventDefault();
}
},
_shouldTrigger: function shouldTrigger(keyName, $e) {
var trigger;
switch (keyName) {
case 'tab':
trigger = !withModifier($e);
break;
default:
trigger = true;
}
return trigger;
},
_checkInputValue: function checkInputValue() {
var inputValue;
var areEquivalent;
var hasDifferentWhitespace;
inputValue = this.getInputValue();
areEquivalent = areQueriesEquivalent(inputValue, this.query);
hasDifferentWhitespace = areEquivalent && this.query ?
this.query.length !== inputValue.length : false;
this.query = inputValue;
if (!areEquivalent) {
this.trigger('queryChanged', this.query);
} else if (hasDifferentWhitespace) {
this.trigger('whitespaceChanged', this.query);
}
},
// ### public
focus: function focus() {
this.$input.focus();
},
blur: function blur() {
this.$input.blur();
},
getQuery: function getQuery() {
return this.query;
},
setQuery: function setQuery(query) {
this.query = query;
},
getInputValue: function getInputValue() {
return this.$input.val();
},
setInputValue: function setInputValue(value, silent) {
if (typeof value === 'undefined') {
value = this.query;
}
this.$input.val(value);
// silent prevents any additional events from being triggered
if (silent) {
this.clearHint();
} else {
this._checkInputValue();
}
},
resetInputValue: function resetInputValue() {
this.setInputValue(this.query, true);
},
getHint: function getHint() {
return this.$hint.val();
},
setHint: function setHint(value) {
this.$hint.val(value);
},
clearHint: function clearHint() {
this.setHint('');
},
clearHintIfInvalid: function clearHintIfInvalid() {
var val;
var hint;
var valIsPrefixOfHint;
var isValid;
val = this.getInputValue();
hint = this.getHint();
valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
isValid = val !== '' && valIsPrefixOfHint && !this.hasOverflow();
if (!isValid) {
this.clearHint();
}
},
getLanguageDirection: function getLanguageDirection() {
return (this.$input.css('direction') || 'ltr').toLowerCase();
},
hasOverflow: function hasOverflow() {
// 2 is arbitrary, just picking a small number to handle edge cases
var constraint = this.$input.width() - 2;
this.$overflowHelper.text(this.getInputValue());
return this.$overflowHelper.width() >= constraint;
},
isCursorAtEnd: function() {
var valueLength;
var selectionStart;
var range;
valueLength = this.$input.val().length;
selectionStart = this.$input[0].selectionStart;
if (_.isNumber(selectionStart)) {
return selectionStart === valueLength;
} else if (document.selection) {
// NOTE: this won't work unless the input has focus, the good news
// is this code should only get called when the input has focus
range = document.selection.createRange();
range.moveStart('character', -valueLength);
return valueLength === range.text.length;
}
return true;
},
destroy: function destroy() {
this.$hint.off('.aa');
this.$input.off('.aa');
this.$hint = this.$input = this.$overflowHelper = null;
}
});
// helper functions
// ----------------
function buildOverflowHelper($input) {
return DOM.element('<pre aria-hidden="true"></pre>')
.css({
// position helper off-screen
position: 'absolute',
visibility: 'hidden',
// avoid line breaks and whitespace collapsing
whiteSpace: 'pre',
// use same font css as input to calculate accurate width
fontFamily: $input.css('font-family'),
fontSize: $input.css('font-size'),
fontStyle: $input.css('font-style'),
fontVariant: $input.css('font-variant'),
fontWeight: $input.css('font-weight'),
wordSpacing: $input.css('word-spacing'),
letterSpacing: $input.css('letter-spacing'),
textIndent: $input.css('text-indent'),
textRendering: $input.css('text-rendering'),
textTransform: $input.css('text-transform')
})
.insertAfter($input);
}
function areQueriesEquivalent(a, b) {
return Input.normalizeQuery(a) === Input.normalizeQuery(b);
}
function withModifier($e) {
return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
}
module.exports = Input;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(setImmediate) {'use strict';
var splitter = /\s+/;
var nextTick = getNextTick();
module.exports = {
onSync: onSync,
onAsync: onAsync,
off: off,
trigger: trigger
};
function on(method, types, cb, context) {
var type;
if (!cb) {
return this;
}
types = types.split(splitter);
cb = context ? bindContext(cb, context) : cb;
this._callbacks = this._callbacks || {};
while (type = types.shift()) {
this._callbacks[type] = this._callbacks[type] || {sync: [], async: []};
this._callbacks[type][method].push(cb);
}
return this;
}
function onAsync(types, cb, context) {
return on.call(this, 'async', types, cb, context);
}
function onSync(types, cb, context) {
return on.call(this, 'sync', types, cb, context);
}
function off(types) {
var type;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
while (type = types.shift()) {
delete this._callbacks[type];
}
return this;
}
function trigger(types) {
var type;
var callbacks;
var args;
var syncFlush;
var asyncFlush;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
args = [].slice.call(arguments, 1);
while ((type = types.shift()) && (callbacks = this._callbacks[type])) { // eslint-disable-line
syncFlush = getFlush(callbacks.sync, this, [type].concat(args));
asyncFlush = getFlush(callbacks.async, this, [type].concat(args));
if (syncFlush()) {
nextTick(asyncFlush);
}
}
return this;
}
function getFlush(callbacks, context, args) {
return flush;
function flush() {
var cancelled;
for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
// only cancel if the callback explicitly returns false
cancelled = callbacks[i].apply(context, args) === false;
}
return !cancelled;
}
}
function getNextTick() {
var nextTickFn;
if (window.setImmediate) { // IE10+
nextTickFn = function nextTickSetImmediate(fn) {
setImmediate(function() { fn(); });
};
} else { // old browsers
nextTickFn = function nextTickSetTimeout(fn) {
setTimeout(function() { fn(); }, 0);
};
}
return nextTickFn;
}
function bindContext(fn, context) {
return fn.bind ?
fn.bind(context) :
function() { fn.apply(context, [].slice.call(arguments, 0)); };
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9).setImmediate))
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var nextTick = __webpack_require__(10).nextTick;
var apply = Function.prototype.apply;
var slice = Array.prototype.slice;
var immediateIds = {};
var nextImmediateId = 0;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) { timeout.close(); };
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// That's not how node.js implements it but the exposed api is the same.
exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
var id = nextImmediateId++;
var args = arguments.length < 2 ? false : slice.call(arguments, 1);
immediateIds[id] = true;
nextTick(function onNextTick() {
if (immediateIds[id]) {
// fn.call() is faster so we optimize for the common use-case
// @see http://jsperf.com/call-apply-segu
if (args) {
fn.apply(null, args);
} else {
fn.call(null);
}
// Prevent ids from leaking
exports.clearImmediate(id);
}
});
return id;
};
exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
delete immediateIds[id];
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9).setImmediate, __webpack_require__(9).clearImmediate))
/***/ },
/* 10 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _ = __webpack_require__(4);
var DOM = __webpack_require__(3);
var EventEmitter = __webpack_require__(8);
var Dataset = __webpack_require__(12);
var css = __webpack_require__(14);
// constructor
// -----------
function Dropdown(o) {
var that = this;
var onSuggestionClick;
var onSuggestionMouseEnter;
var onSuggestionMouseLeave;
o = o || {};
if (!o.menu) {
_.error('menu is required');
}
if (!_.isArray(o.datasets) && !_.isObject(o.datasets)) {
_.error('1 or more datasets required');
}
if (!o.datasets) {
_.error('datasets is required');
}
this.isOpen = false;
this.isEmpty = true;
this.minLength = o.minLength || 0;
this.cssClasses = _.mixin({}, css.defaultClasses, o.cssClasses || {});
this.templates = {};
// bound functions
onSuggestionClick = _.bind(this._onSuggestionClick, this);
onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
var cssClass = _.className(this.cssClasses.prefix, this.cssClasses.suggestion);
this.$menu = DOM.element(o.menu)
.on('click.aa', cssClass, onSuggestionClick)
.on('mouseenter.aa', cssClass, onSuggestionMouseEnter)
.on('mouseleave.aa', cssClass, onSuggestionMouseLeave);
if (o.templates && o.templates.header) {
this.templates.header = _.templatify(o.templates.header);
this.$menu.prepend(this.templates.header());
}
if (o.templates && o.templates.empty) {
this.templates.empty = _.templatify(o.templates.empty);
this.$empty = DOM.element('<div class="' +
_.className(this.cssClasses.prefix, this.cssClasses.empty, true) + '">' +
'</div>');
this.$menu.append(this.$empty);
}
this.datasets = _.map(o.datasets, function(oDataset) {
return initializeDataset(that.$menu, oDataset, o.cssClasses);
});
_.each(this.datasets, function(dataset) {
var root = dataset.getRoot();
if (root && root.parent().length === 0) {
that.$menu.append(root);
}
dataset.onSync('rendered', that._onRendered, that);
});
if (o.templates && o.templates.footer) {
this.templates.footer = _.templatify(o.templates.footer);
this.$menu.append(this.templates.footer());
}
}
// instance methods
// ----------------
_.mixin(Dropdown.prototype, EventEmitter, {
// ### private
_onSuggestionClick: function onSuggestionClick($e) {
this.trigger('suggestionClicked', DOM.element($e.currentTarget));
},
_onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
var elt = DOM.element($e.currentTarget);
if (elt.hasClass(_.className(this.cssClasses.prefix, this.cssClasses.cursor, true))) {
// we're already on the cursor
// => we're probably entering it again after leaving it for a nested div
return;
}
this._removeCursor();
this._setCursor(elt, false);
},
_onSuggestionMouseLeave: function onSuggestionMouseLeave($e) {
// $e.relatedTarget is the `EventTarget` the pointing device entered to
if ($e.relatedTarget) {
var elt = DOM.element($e.relatedTarget);
if (elt.closest('.' + _.className(this.cssClasses.prefix, this.cssClasses.cursor, true)).length > 0) {
// our father is a cursor
// => it means we're just leaving the suggestion for a nested div
return;
}
}
this._removeCursor();
this.trigger('cursorRemoved');
},
_onRendered: function onRendered(e, query) {
this.isEmpty = _.every(this.datasets, isDatasetEmpty);
if (this.isEmpty) {
if (query.length >= this.minLength) {
this.trigger('empty');
}
if (this.$empty) {
if (query.length < this.minLength) {
this._hide();
} else {
var html = this.templates.empty({
query: this.datasets[0] && this.datasets[0].query
});
this.$empty.html(html);
this._show();
}
} else if (_.any(this.datasets, hasEmptyTemplate)) {
if (query.length < this.minLength) {
this._hide();
} else {
this._show();
}
} else {
this._hide();
}
} else if (this.isOpen) {
if (this.$empty) {
this.$empty.empty();
}
if (query.length >= this.minLength) {
this._show();
} else {
this._hide();
}
}
this.trigger('datasetRendered');
function isDatasetEmpty(dataset) {
return dataset.isEmpty();
}
function hasEmptyTemplate(dataset) {
return dataset.templates && dataset.templates.empty;
}
},
_hide: function() {
this.$menu.hide();
},
_show: function() {
// can't use jQuery#show because $menu is a span element we want
// display: block; not dislay: inline;
this.$menu.css('display', 'block');
this.trigger('shown');
},
_getSuggestions: function getSuggestions() {
return this.$menu.find(_.className(this.cssClasses.prefix, this.cssClasses.suggestion));
},
_getCursor: function getCursor() {
return this.$menu.find(_.className(this.cssClasses.prefix, this.cssClasses.cursor)).first();
},
_setCursor: function setCursor($el, updateInput) {
$el.first().addClass(_.className(this.cssClasses.prefix, this.cssClasses.cursor, true));
this.trigger('cursorMoved', updateInput);
},
_removeCursor: function removeCursor() {
this._getCursor().removeClass(_.className(this.cssClasses.prefix, this.cssClasses.cursor, true));
},
_moveCursor: function moveCursor(increment) {
var $suggestions;
var $oldCursor;
var newCursorIndex;
var $newCursor;
if (!this.isOpen) {
return;
}
$oldCursor = this._getCursor();
$suggestions = this._getSuggestions();
this._removeCursor();
// shifting before and after modulo to deal with -1 index
newCursorIndex = $suggestions.index($oldCursor) + increment;
newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
if (newCursorIndex === -1) {
this.trigger('cursorRemoved');
return;
} else if (newCursorIndex < -1) {
newCursorIndex = $suggestions.length - 1;
}
this._setCursor($newCursor = $suggestions.eq(newCursorIndex), true);
// in the case of scrollable overflow
// make sure the cursor is visible in the menu
this._ensureVisible($newCursor);
},
_ensureVisible: function ensureVisible($el) {
var elTop;
var elBottom;
var menuScrollTop;
var menuHeight;
elTop = $el.position().top;
elBottom = elTop + $el.height() +
parseInt($el.css('margin-top'), 10) +
parseInt($el.css('margin-bottom'), 10);
menuScrollTop = this.$menu.scrollTop();
menuHeight = this.$menu.height() +
parseInt(this.$menu.css('paddingTop'), 10) +
parseInt(this.$menu.css('paddingBottom'), 10);
if (elTop < 0) {
this.$menu.scrollTop(menuScrollTop + elTop);
} else if (menuHeight < elBottom) {
this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
}
},
// ### public
close: function close() {
if (this.isOpen) {
this.isOpen = false;
this._removeCursor();
this._hide();
this.trigger('closed');
}
},
open: function open() {
if (!this.isOpen) {
this.isOpen = true;
if (!this.isEmpty) {
this._show();
}
this.trigger('opened');
}
},
setLanguageDirection: function setLanguageDirection(dir) {
this.$menu.css(dir === 'ltr' ? css.ltr : css.rtl);
},
moveCursorUp: function moveCursorUp() {
this._moveCursor(-1);
},
moveCursorDown: function moveCursorDown() {
this._moveCursor(+1);
},
getDatumForSuggestion: function getDatumForSuggestion($el) {
var datum = null;
if ($el.length) {
datum = {
raw: Dataset.extractDatum($el),
value: Dataset.extractValue($el),
datasetName: Dataset.extractDatasetName($el)
};
}
return datum;
},
getDatumForCursor: function getDatumForCursor() {
return this.getDatumForSuggestion(this._getCursor().first());
},
getDatumForTopSuggestion: function getDatumForTopSuggestion() {
return this.getDatumForSuggestion(this._getSuggestions().first());
},
cursorTopSuggestion: function cursorTopSuggestion() {
this._setCursor(this._getSuggestions().first(), false);
},
update: function update(query) {
_.each(this.datasets, updateDataset);
function updateDataset(dataset) {
dataset.update(query);
}
},
empty: function empty() {
_.each(this.datasets, clearDataset);
this.isEmpty = true;
function clearDataset(dataset) {
dataset.clear();
}
},
isVisible: function isVisible() {
return this.isOpen && !this.isEmpty;
},
destroy: function destroy() {
this.$menu.off('.aa');
this.$menu = null;
_.each(this.datasets, destroyDataset);
function destroyDataset(dataset) {
dataset.destroy();
}
}
});
// helper functions
// ----------------
Dropdown.Dataset = Dataset;
function initializeDataset($menu, oDataset, cssClasses) {
return new Dropdown.Dataset(_.mixin({$menu: $menu, cssClasses: cssClasses}, oDataset));
}
module.exports = Dropdown;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var datasetKey = 'aaDataset';
var valueKey = 'aaValue';
var datumKey = 'aaDatum';
var _ = __webpack_require__(4);
var DOM = __webpack_require__(3);
var html = __webpack_require__(13);
var css = __webpack_require__(14);
var EventEmitter = __webpack_require__(8);
// constructor
// -----------
function Dataset(o) {
o = o || {};
o.templates = o.templates || {};
if (!o.source) {
_.error('missing source');
}
if (o.name && !isValidName(o.name)) {
_.error('invalid dataset name: ' + o.name);
}
// tracks the last query the dataset was updated for
this.query = null;
this._isEmpty = true;
this.highlight = !!o.highlight;
this.name = typeof o.name === 'undefined' || o.name === null ? _.getUniqueId() : o.name;
this.source = o.source;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.templates = getTemplates(o.templates, this.displayFn);
this.cssClasses = _.mixin({}, css.defaultClasses, o.cssClasses || {});
var clazz = _.className(this.cssClasses.prefix, this.cssClasses.dataset);
this.$el = o.$menu && o.$menu.find(clazz + '-' + this.name).length > 0 ?
DOM.element(o.$menu.find(clazz + '-' + this.name)[0]) :
DOM.element(
html.dataset.replace('%CLASS%', this.name)
.replace('%PREFIX%', this.cssClasses.prefix)
.replace('%DATASET%', this.cssClasses.dataset)
);
this.$menu = o.$menu;
}
// static methods
// --------------
Dataset.extractDatasetName = function extractDatasetName(el) {
return DOM.element(el).data(datasetKey);
};
Dataset.extractValue = function extractValue(el) {
return DOM.element(el).data(valueKey);
};
Dataset.extractDatum = function extractDatum(el) {
var datum = DOM.element(el).data(datumKey);
if (typeof datum === 'string') {
// Zepto has an automatic deserialization of the
// JSON encoded data attribute
datum = JSON.parse(datum);
}
return datum;
};
// instance methods
// ----------------
_.mixin(Dataset.prototype, EventEmitter, {
// ### private
_render: function render(query, suggestions) {
if (!this.$el) {
return;
}
var that = this;
var hasSuggestions;
var renderArgs = [].slice.call(arguments, 2);
this.$el.empty();
hasSuggestions = suggestions && suggestions.length;
this._isEmpty = !hasSuggestions;
if (!hasSuggestions && this.templates.empty) {
this.$el
.html(getEmptyHtml.apply(this, renderArgs))
.prepend(that.templates.header ? getHeaderHtml.apply(this, renderArgs) : null)
.append(that.templates.footer ? getFooterHtml.apply(this, renderArgs) : null);
} else if (hasSuggestions) {
this.$el
.html(getSuggestionsHtml.apply(this, renderArgs))
.prepend(that.templates.header ? getHeaderHtml.apply(this, renderArgs) : null)
.append(that.templates.footer ? getFooterHtml.apply(this, renderArgs) : null);
}
if (this.$menu) {
this.$menu.addClass(this.cssClasses.prefix + '-' + (hasSuggestions ? 'with' : 'without') + '-' + this.name)
.removeClass(this.cssClasses.prefix + '-' + (hasSuggestions ? 'without' : 'with') + '-' + this.name);
}
this.trigger('rendered', query);
function getEmptyHtml() {
var args = [].slice.call(arguments, 0);
args = [{query: query, isEmpty: true}].concat(args);
return that.templates.empty.apply(this, args);
}
function getSuggestionsHtml() {
var args = [].slice.call(arguments, 0);
var $suggestions;
var nodes;
var self = this;
var suggestionsHtml = html.suggestions.
replace('%PREFIX%', this.cssClasses.prefix).
replace('%SUGGESTIONS%', this.cssClasses.suggestions);
$suggestions = DOM.element(suggestionsHtml).css(css.suggestions);
// jQuery#append doesn't support arrays as the first argument
// until version 1.8, see http://bugs.jquery.com/ticket/11231
nodes = _.map(suggestions, getSuggestionNode);
$suggestions.append.apply($suggestions, nodes);
return $suggestions;
function getSuggestionNode(suggestion) {
var $el;
var suggestionHtml = html.suggestion.
replace('%PREFIX%', self.cssClasses.prefix).
replace('%SUGGESTION%', self.cssClasses.suggestion);
$el = DOM.element(suggestionHtml)
.append(that.templates.suggestion.apply(this, [suggestion].concat(args)));
$el.data(datasetKey, that.name);
$el.data(valueKey, that.displayFn(suggestion) || undefined); // this led to undefined return value
$el.data(datumKey, JSON.stringify(suggestion));
$el.children().each(function() { DOM.element(this).css(css.suggestionChild); });
return $el;
}
}
function getHeaderHtml() {
var args = [].slice.call(arguments, 0);
args = [{query: query, isEmpty: !hasSuggestions}].concat(args);
return that.templates.header.apply(this, args);
}
function getFooterHtml() {
var args = [].slice.call(arguments, 0);
args = [{query: query, isEmpty: !hasSuggestions}].concat(args);
return that.templates.footer.apply(this, args);
}
},
// ### public
getRoot: function getRoot() {
return this.$el;
},
update: function update(query) {
var that = this;
this.query = query;
this.canceled = false;
this.source(query, render);
function render(suggestions) {
// if the update has been canceled or if the query has changed
// do not render the suggestions as they've become outdated
if (!that.canceled && query === that.query) {
// concat all the other arguments that could have been passed
// to the render function, and forward them to _render
var args = [].slice.call(arguments, 1);
args = [query, suggestions].concat(args);
that._render.apply(that, args);
}
}
},
cancel: function cancel() {
this.canceled = true;
},
clear: function clear() {
this.cancel();
this.$el.empty();
this.trigger('rendered', '');
},
isEmpty: function isEmpty() {
return this._isEmpty;
},
destroy: function destroy() {
this.$el = null;
}
});
// helper functions
// ----------------
function getDisplayFn(display) {
display = display || 'value';
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) {
return obj[display];
}
}
function getTemplates(templates, displayFn) {
return {
empty: templates.empty && _.templatify(templates.empty),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return '<p>' + displayFn(context) + '</p>';
}
}
function isValidName(str) {
// dashes, underscores, letters, and numbers
return (/^[_a-zA-Z0-9-]+$/).test(str);
}
module.exports = Dataset;
/***/ },
/* 13 */
/***/ function(module, exports) {
'use strict';
module.exports = {
wrapper: '<span class="%ROOT%"></span>',
dropdown: '<span class="%PREFIX%-%DROPDOWN_MENU%"></span>',
dataset: '<div class="%PREFIX%-%DATASET%-%CLASS%"></div>',
suggestions: '<span class="%PREFIX%-%SUGGESTIONS%"></span>',
suggestion: '<div class="%PREFIX%-%SUGGESTION%"></div>'
};
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _ = __webpack_require__(4);
var css = {
wrapper: {
position: 'relative',
display: 'inline-block'
},
hint: {
position: 'absolute',
top: '0',
left: '0',
borderColor: 'transparent',
boxShadow: 'none',
// #741: fix hint opacity issue on iOS
opacity: '1'
},
input: {
position: 'relative',
verticalAlign: 'top',
backgroundColor: 'transparent'
},
inputWithNoHint: {
position: 'relative',
verticalAlign: 'top'
},
dropdown: {
position: 'absolute',
top: '100%',
left: '0',
zIndex: '100',
display: 'none'
},
suggestions: {
display: 'block'
},
suggestion: {
whiteSpace: 'nowrap',
cursor: 'pointer'
},
suggestionChild: {
whiteSpace: 'normal'
},
ltr: {
left: '0',
right: 'auto'
},
rtl: {
left: 'auto',
right: '0'
},
defaultClasses: {
root: 'algolia-autocomplete',
prefix: 'aa',
dropdownMenu: 'dropdown-menu',
input: 'input',
hint: 'hint',
suggestions: 'suggestions',
suggestion: 'suggestion',
cursor: 'cursor',
dataset: 'dataset',
empty: 'empty'
}
};
// ie specific styling
if (_.isMsie()) {
// ie6-8 (and 9?) doesn't fire hover and click events for elements with
// transparent backgrounds, for a workaround, use 1x1 transparent gif
_.mixin(css.input, {
backgroundImage: 'url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)'
});
}
// ie7 and under specific styling
if (_.isMsie() && _.isMsie() <= 7) {
// if someone can tell me why this is necessary to align
// the hint with the query in ie7, i'll send you $5 - @JakeHarding
_.mixin(css.input, {marginTop: '-1px'});
}
module.exports = css;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = {
hits: __webpack_require__(16),
popularIn: __webpack_require__(17)
};
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _ = __webpack_require__(4);
module.exports = function search(index, params) {
return sourceFn;
function sourceFn(query, cb) {
index.search(query, params, function(error, content) {
if (error) {
_.error(error.message);
return;
}
cb(content.hits, content);
});
}
};
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _ = __webpack_require__(4);
module.exports = function popularIn(index, params, details, options) {
if (!details.source) {
return _.error("Missing 'source' key");
}
var source = _.isFunction(details.source) ? details.source : function(hit) { return hit[details.source]; };
if (!details.index) {
return _.error("Missing 'index' key");
}
var detailsIndex = details.index;
options = options || {};
return sourceFn;
function sourceFn(query, cb) {
index.search(query, params, function(error, content) {
if (error) {
_.error(error.message);
return;
}
if (content.hits.length > 0) {
var first = content.hits[0];
var detailsParams = _.mixin({hitsPerPage: 0}, details);
delete detailsParams.source; // not a query parameter
delete detailsParams.index; // not a query parameter
detailsIndex.search(source(first), detailsParams, function(error2, content2) {
if (error2) {
_.error(error2.message);
return;
}
var suggestions = [];
// add the 'all department' entry before others
if (options.includeAll) {
var label = options.allTitle || 'All departments';
suggestions.push(_.mixin({
facet: {value: label, count: content2.nbHits}
}, _.cloneDeep(first)));
}
// enrich the first hit iterating over the facets
_.each(content2.facets, function(values, facet) {
_.each(values, function(count, value) {
suggestions.push(_.mixin({
facet: {facet: facet, value: value, count: count}
}, _.cloneDeep(first)));
});
});
// append all other hits
for (var i = 1; i < content.hits.length; ++i) {
suggestions.push(content.hits[i]);
}
cb(suggestions, content);
});
return;
}
cb([]);
});
}
};
/***/ }
/******/ ]); | MadhavBitra/jsdelivr | files/autocomplete.js/0.21.8/autocomplete.angular.js | JavaScript | mit | 64,074 |
/* ==========================================================
* GitGraph v1.1.0
* https://github.com/nicoespeon/gitgraph.js
* ==========================================================
* Copyright (c) 2015 Nicolas CARLO (@nicoespeon) ٩(^‿^)۶
* Copyright (c) 2015 Fabien BERNARD (@fabien0102) ✌(✰‿✰)✌
*
* GitGraph.js may be freely distributed under the MIT Licence
* ========================================================== */
(function () {
"use strict";
/**
* Emit an event on the given element.
* @param {HTMLElement} element - DOM element to trigger the event on.
* @param {String} eventName - Name of the triggered event.
* @param {Object} [data={}] - Custom data to attach to the event.
* @private
*/
function _emitEvent ( element, eventName, data ) {
var event;
if ( document.createEvent ) {
event = document.createEvent( "HTMLEvents" );
event.initEvent( eventName, true, true );
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.data = data || {};
if ( document.createEvent ) {
element.dispatchEvent( event );
} else {
element.fireEvent( "on" + event.eventType, event );
}
}
/**
* GitGraph
*
* @constructor
*
* @param {Object} options - GitGraph options
* @param {String} [options.elementId = "gitGraph"] - Id of the canvas container
* @param {Template|String|Object} [options.template] - Template of the graph
* @param {String} [options.author = "Sergio Flores <saxo-guy@epic.com>"] - Default author for commits
* @param {String} [options.mode = (null|"compact")] - Display mode
* @param {HTMLElement} [options.canvas] - DOM canvas (ex: document.getElementById("id"))
* @param {String} [options.orientation = ("vertical-reverse"|"horizontal"|"horizontal-reverse")] - Graph orientation
*
* @this GitGraph
**/
function GitGraph ( options ) {
// Options
options = (typeof options === "object") ? options : {};
this.elementId = (typeof options.elementId === "string") ? options.elementId : "gitGraph";
this.author = (typeof options.author === "string") ? options.author : "Sergio Flores <saxo-guy@epic.com>";
// Template management
if ( (typeof options.template === "string")
|| (typeof options.template === "object") ) {
this.template = this.newTemplate( options.template );
}
else if ( options.template instanceof Template ) {
this.template = options.template;
}
else {
this.template = this.newTemplate( "metro" );
}
this.mode = options.mode || null;
if ( this.mode === "compact" ) {
this.template.commit.message.display = false;
}
// Orientation
switch ( options.orientation ) {
case "vertical-reverse" :
this.template.commit.spacingY *= -1;
this.orientation = "vertical-reverse";
this.template.branch.labelRotation = 0;
this.template.commit.tag.spacingY *= -1;
break;
case "horizontal" :
this.template.commit.message.display = false;
this.template.commit.spacingX = this.template.commit.spacingY;
this.template.branch.spacingY = this.template.branch.spacingX;
this.template.commit.spacingY = 0;
this.template.branch.spacingX = 0;
this.orientation = "horizontal";
this.template.branch.labelRotation = -90;
this.template.commit.tag.spacingX = -this.template.commit.spacingX;
this.template.commit.tag.spacingY = this.template.branch.spacingY;
break;
case "horizontal-reverse" :
this.template.commit.message.display = false;
this.template.commit.spacingX = -this.template.commit.spacingY;
this.template.branch.spacingY = this.template.branch.spacingX;
this.template.commit.spacingY = 0;
this.template.branch.spacingX = 0;
this.orientation = "horizontal-reverse";
this.template.branch.labelRotation = 90;
this.template.commit.tag.spacingX = -this.template.commit.spacingY;
this.template.commit.tag.spacingY = this.template.branch.spacingY;
break;
default:
this.orientation = "vertical";
this.template.branch.labelRotation = 0;
break;
}
this.marginX = this.template.branch.spacingX + this.template.commit.dot.size * 2;
this.marginY = this.template.branch.spacingY + this.template.commit.dot.size * 2;
this.offsetX = 0;
this.offsetY = 0;
// Canvas init
this.canvas = document.getElementById( this.elementId ) || options.canvas;
this.context = this.canvas.getContext( "2d" );
this.context.textBaseline = "center";
// Tooltip layer
this.tooltip = document.createElement( "div" );
this.tooltip.className = "gitgraph-tooltip";
this.tooltip.style.position = "fixed";
this.tooltip.style.display = "none";
// Add tooltip div into body
document.body.appendChild( this.tooltip );
// Navigation vars
this.HEAD = null;
this.branchs = [];
this.commits = [];
// Utilities
this.columnMax = 0; // nb of column for message position
this.commitOffsetX = 0;
this.commitOffsetY = 0;
// Bindings
var mouseMoveOptions = {
handleEvent: this.hover,
gitgraph: this
};
this.canvas.addEventListener( "mousemove", mouseMoveOptions, false );
var mouseDownOptions = {
handleEvent: this.click,
gitgraph: this
};
this.canvas.addEventListener( "mousedown", mouseDownOptions, false );
// Render on window resize
window.onresize = this.render.bind( this );
}
/**
* Create new branch
*
* @param {(String | Object)} options - Branch name | Options of Branch
*
* @see Branch
* @this GitGraph
*
* @return {Branch} New branch
**/
GitGraph.prototype.branch = function ( options ) {
// Options
if ( typeof options === "string" ) {
var name = options;
options = {};
options.name = name;
}
options = (typeof options === "object") ? options : {};
options.parent = this;
options.parentBranch = options.parentBranch || this.HEAD;
// Add branch
var branch = new Branch( options );
this.branchs.push( branch );
// Return
return branch;
};
/**
* Create new orphan branch
*
* @param {(String | Object)} options - Branch name | Options of Branch
*
* @see Branch
* @this GitGraph
*
* @return {Branch} New branch
**/
GitGraph.prototype.orphanBranch = function ( options ) {
// Options
if ( typeof options === "string" ) {
var name = options;
options = {};
options.name = name;
}
options = (typeof options === "object") ? options : {};
options.parent = this;
// Add branch
var branch = new Branch( options );
this.branchs.push( branch );
// Return
return branch;
};
/**
* Commit on HEAD
*
* @param {Object} options - Options of commit
*
* @see Commit
* @this GitGraph
*
* @return {GitGraph} this - Return the main object so we can chain
**/
GitGraph.prototype.commit = function ( options ) {
this.HEAD.commit( options );
// Return the main object so we can chain
return this;
};
/**
* Create a new template
*
* @param {(String|Object)} options - The template name, or the template options
*
* @return {Template}
**/
GitGraph.prototype.newTemplate = function ( options ) {
if ( typeof options === "string" ) {
return new Template().get( options );
}
return new Template( options );
};
/**
* Render the canvas
*
* @this GitGraph
**/
GitGraph.prototype.render = function () {
var backingStorePixelRatio;
var scalingFactor;
// Account for high-resolution displays
scalingFactor = 1;
if ( window.devicePixelRatio ) {
backingStorePixelRatio = this.context.webkitBackingStorePixelRatio ||
this.context.mozBackingStorePixelRatio ||
this.context.msBackingStorePixelRatio ||
this.context.oBackingStorePixelRatio ||
this.context.backingStorePixelRatio || 1;
scalingFactor *= window.devicePixelRatio / backingStorePixelRatio;
}
// Resize canvas
var unscaledResolution = {
x: Math.abs( (this.columnMax + 1 ) * this.template.branch.spacingX )
+ Math.abs( this.commitOffsetX )
+ this.marginX * 2,
y: Math.abs( (this.columnMax + 1 ) * this.template.branch.spacingY )
+ Math.abs( this.commitOffsetY )
+ this.marginY * 2
};
if ( this.template.commit.message.display ) {
unscaledResolution.x += 800;
}
unscaledResolution.x += this.template.commit.widthExtension;
this.canvas.style.width = unscaledResolution.x + "px";
this.canvas.style.height = unscaledResolution.y + "px";
this.canvas.width = unscaledResolution.x * scalingFactor;
this.canvas.height = unscaledResolution.y * scalingFactor;
this.context.scale( scalingFactor, scalingFactor );
// Clear All
this.context.clearRect( 0, 0, this.canvas.width, this.canvas.height );
// Add some margin
this.context.translate( this.marginX, this.marginY );
// Translate for inverse orientation
if ( this.template.commit.spacingY > 0 ) {
this.context.translate( 0, this.canvas.height - this.marginY * 2 );
this.offsetY = this.canvas.height - this.marginY * 2;
}
if ( this.template.commit.spacingX > 0 ) {
this.context.translate( this.canvas.width - this.marginX * 2, 0 );
this.offsetX = this.canvas.width - this.marginX * 2;
}
// Render branchs
for ( var i = this.branchs.length - 1, branch; !!(branch = this.branchs[ i ]); i-- ) {
branch.render();
}
this.tagNum = 0;
// Render commits after to put them on the foreground
for ( var j = 0, commit; !!(commit = this.commits[ j ]); j++ ) {
commit.render();
}
};
/**
* A callback for each commit
*
* @callback commitCallback
* @param {Commit} commit - A commit
* @param {boolean} mouseOver - True, if the mouse is currently hovering over the commit
*/
/**
* Hover event on commit dot
*
* @param {MouseEvent} event - Mouse event
* @param {commitCallback} callbackFn - A callback function that will be called for each commit
*
* @self Gitgraph
**/
GitGraph.prototype.applyCommits = function(event, callbackFn) {
// Fix firefox MouseEvent
if ( typeof InstallTrigger !== "undefined" )/* == (is Firefox) */ {
event.offsetX = event.offsetX ? event.offsetX : event.layerX;
event.offsetY = event.offsetY ? event.offsetY : event.layerY;
event.x = event.x ? event.x : event.clientX;
event.y = event.y ? event.y : event.clientY;
}
for ( var i = 0, commit; !!(commit = this.commits[ i ]); i++ ) {
var distanceX = (commit.x + this.offsetX + this.marginX - event.offsetX);
var distanceY = (commit.y + this.offsetY + this.marginY - event.offsetY);
var distanceBetweenCommitCenterAndMouse = Math.sqrt( Math.pow( distanceX, 2 ) + Math.pow( distanceY, 2 ) );
var isOverCommit = distanceBetweenCommitCenterAndMouse < this.template.commit.dot.size;
callbackFn(commit, isOverCommit);
}
};
/**
* Hover event on commit dot
*
* @param {MouseEvent} event - Mouse event
*
* @self Gitgraph
**/
GitGraph.prototype.hover = function ( event ) {
var self = this.gitgraph;
var isOut = true;
function showCommitTooltip (commit) {
self.tooltip.style.left = event.x + "px"; // TODO Scroll bug
self.tooltip.style.top = event.y + "px"; // TODO Scroll bug
if (self.template.commit.tooltipHTMLFormatter !== null) {
self.tooltip.innerHTML = self.template.commit.tooltipHTMLFormatter(commit);
} else {
self.tooltip.textContent = commit.sha1 + " - " + commit.message;
}
self.tooltip.style.display = "block";
}
function emitMouseoverEvent (commit) {
var mouseoverEventOptions = {
author: commit.author,
message: commit.message,
date: commit.date,
sha1: commit.sha1
};
_emitEvent( self.canvas, "commit:mouseover", mouseoverEventOptions );
}
self.applyCommits(event, function(commit, isOverCommit) {
if ( isOverCommit ) {
if ( !self.template.commit.message.display ) {
showCommitTooltip(commit);
}
if ( !commit.isMouseover ) {
emitMouseoverEvent(commit);
}
isOut = false;
commit.isMouseover = true;
} else {
commit.isMouseover = false;
}
});
if ( isOut ) {
self.tooltip.style.display = "none";
}
};
/**
* Click event on commit dot
*
* @param {MouseEvent} event - Mouse event
*
* @self Gitgraph
**/
GitGraph.prototype.click = function ( event ) {
this.gitgraph.applyCommits(event, function(commit, isOverCommit) {
if (!isOverCommit) {
return;
}
if (commit.onClick !== null) {
commit.onClick(commit, true);
}
});
};
// --------------------------------------------------------------------
// ----------------------- Branch ------------------------
// --------------------------------------------------------------------
/**
* Branch
*
* @constructor
*
* @param {Object} options - Options of branch
* @param {GitGraph} options.parent - GitGraph constructor
* @param {Branch} [options.parentBranch] - Parent branch
* @param {String} [options.name = "no-name"] - Branch name
*
* @this Branch
**/
function Branch ( options ) {
// Check integrity
if ( options.parent instanceof GitGraph === false ) {
return;
}
// Options
options = (typeof options === "object") ? options : {};
this.parent = options.parent;
this.parentBranch = options.parentBranch;
this.name = (typeof options.name === "string") ? options.name : "no-name";
this.context = this.parent.context;
this.template = this.parent.template;
this.lineWidth = options.lineWidth || this.template.branch.lineWidth;
this.lineDash = options.lineDash || this.template.branch.lineDash;
this.showLabel = booleanOptionOr(options.showLabel, this.template.branch.showLabel);
this.spacingX = this.template.branch.spacingX;
this.spacingY = this.template.branch.spacingY;
this.size = 0;
this.height = 0;
this.width = 0;
this.commits = [];
this.path = []; // Path to draw, this is an array of points {x, y, type("start"|"join"|"end")}
// Column number calculation for auto-color & auto-offset
if ( typeof options.column === "number" ) {
this.column = options.column;
} else {
this.column = 0;
this.calculColumn();
}
this.parent.columnMax = (this.column > this.parent.columnMax) ? this.column : this.parent.columnMax;
// Options with auto value
this.offsetX = this.column * this.spacingX;
this.offsetY = this.column * this.spacingY;
var columnIndex = (this.column % this.template.colors.length);
this.color = options.color || this.template.branch.color || this.template.colors[ columnIndex ];
// Checkout on this new branch
this.checkout();
}
/**
* Create new branch
*
* @param {(String | Object)} options - Branch name | Options of Branch
*
* @see Branch
* @this Branch
*
* @return {Branch} New Branch
**/
Branch.prototype.branch = function ( options ) {
// Options
if ( typeof options === "string" ) {
var name = options;
options = {};
options.name = name;
}
options = (typeof options === "object") ? options : {};
options.parent = this.parent;
options.parentBranch = options.parentBranch || this;
// Add branch
var branch = new Branch( options );
this.parent.branchs.push( branch );
// Return
return branch;
};
/**
* Render the branch
*
* @this Branch
**/
Branch.prototype.render = function () {
this.context.beginPath();
for ( var i = 0, point; !!(point = this.path[ i ]); i++ ) {
if ( point.type === "start" ) {
this.context.moveTo( point.x, point.y );
} else {
if ( this.template.branch.mergeStyle === "bezier" ) {
var path = this.path[ i - 1 ];
this.context.bezierCurveTo(
path.x - this.template.commit.spacingX / 2, path.y - this.template.commit.spacingY / 2,
point.x + this.template.commit.spacingX / 2, point.y + this.template.commit.spacingY / 2,
point.x, point.y
);
} else {
this.context.lineTo( point.x, point.y );
}
}
}
this.context.lineWidth = this.lineWidth;
this.context.strokeStyle = this.color;
if ( this.context.setLineDash !== undefined ) {
this.context.setLineDash( this.lineDash );
}
this.context.stroke();
this.context.closePath();
};
/**
* Add a commit
*
* @param {(String | Object)} [options] - Message | Options of commit
* @param {String} [options.detailId] - Id of detail DOM Element
*
* @see Commit
*
* @this Branch
**/
Branch.prototype.commit = function ( options ) {
if ( typeof (options) === "string" ) {
var message = options;
options = { message: message };
} else if ( typeof (options) !== "object" ) {
options = {};
}
options.arrowDisplay = this.template.arrow.active;
options.branch = this;
var columnIndex = (this.column % this.template.colors.length);
options.color = options.color || this.template.commit.color || this.template.colors[ columnIndex ];
options.parent = this.parent;
options.parentCommit = options.parentCommit || this.commits.slice( -1 )[ 0 ];
// Special compact mode
if ( this.parent.mode === "compact"
&& this.parent.commits.slice( -1 )[ 0 ]
&& this.parent.commits.slice( -1 )[ 0 ].branch !== options.branch
&& options.branch.commits.length
&& options.type !== "mergeCommit" ) {
this.parent.commitOffsetX -= this.template.commit.spacingX;
this.parent.commitOffsetY -= this.template.commit.spacingY;
}
options.messageColor = options.messageColor || this.template.commit.message.color || options.color || null;
options.labelColor = options.labelColor || this.template.branch.labelColor || options.color || null;
options.tagColor = options.tagColor || this.template.commit.tag.color || options.color || null;
options.dotColor = options.dotColor || this.template.commit.dot.color || options.color || null;
options.x = this.offsetX - this.parent.commitOffsetX;
options.y = this.offsetY - this.parent.commitOffsetY;
// Detail
var isVertical = this.parent.orientation === "vertical";
var isNotCompact = this.parent.mode !== "compact";
if ( typeof options.detailId === "string" && isVertical && isNotCompact ) {
options.detail = document.getElementById( options.detailId );
} else {
options.detail = null;
}
// Check collision (Cause of special compact mode)
var previousCommit = options.branch.commits.slice( -1 )[ 0 ] || {};
var commitPosition = options.x + options.y;
var previousCommitPosition = previousCommit.x + previousCommit.y;
var isCommitAtSamePlaceThanPreviousOne = (commitPosition === previousCommitPosition);
if ( isCommitAtSamePlaceThanPreviousOne ) {
this.parent.commitOffsetX += this.template.commit.spacingX;
this.parent.commitOffsetY += this.template.commit.spacingY;
options.x = this.offsetX - this.parent.commitOffsetX;
options.y = this.offsetY - this.parent.commitOffsetY;
}
// Fork case: Parent commit from parent branch
if ( options.parentCommit instanceof Commit === false && this.parentBranch instanceof Branch ) {
options.parentCommit = this.parentBranch.commits.slice( -1 )[ 0 ];
}
// First commit
var isFirstBranch = options.parentCommit instanceof Commit;
var isPathBeginning = this.path.length === 0;
options.showLabel = (isPathBeginning && this.showLabel) ? true : false;
if ( options.showLabel ) {
options.x -= this.template.commit.spacingX;
options.y -= this.template.commit.spacingY;
}
var commit = new Commit( options );
this.commits.push( commit );
// Add point(s) to path
var point = {
x: commit.x,
y: commit.y,
type: "join"
};
if ( isFirstBranch && isPathBeginning ) {
var parent = {
x: commit.parentCommit.branch.offsetX - this.parent.commitOffsetX + this.template.commit.spacingX,
y: commit.parentCommit.branch.offsetY - this.parent.commitOffsetY + this.template.commit.spacingY,
type: "start"
};
this.path.push( JSON.parse( JSON.stringify( parent ) ) ); // Elegant way for cloning an object
parent.type = "join";
this.parentBranch.path.push( parent );
} else if ( isPathBeginning ) {
point.type = "start";
}
// Increment commitOffset for next commit position
this.path.push( point );
this.parent.commitOffsetX += this.template.commit.spacingX * (options.showLabel ? 2 : 1);
this.parent.commitOffsetY += this.template.commit.spacingY * (options.showLabel ? 2 : 1);
// Add height of detail div (normal vertical mode only)
if ( commit.detail !== null ) {
commit.detail.style.display = "block";
this.parent.commitOffsetY -= commit.detail.clientHeight - 40;
}
// Auto-render
this.parent.render();
// Return the main object so we can chain
return this;
};
/**
* Checkout onto this branch
*
* @this Branch
**/
Branch.prototype.checkout = function () {
this.parent.HEAD = this;
};
/**
* Delete this branch
*
* @this Branch
**/
Branch.prototype.delete = function () {
this.isfinish = true;
};
/**
* Merge branch
*
* @param {Branch} [target = this.parent.HEAD]
* @param {(String | Object)} [commitOptions] - Message | Options of commit
*
* @this Branch
*
* @return {Branch} this
**/
Branch.prototype.merge = function ( target, commitOptions ) {
// Merge target
var targetBranch = target || this.parent.HEAD;
// Check integrity of target
if ( targetBranch instanceof Branch === false || targetBranch === this ) {
return;
}
// Merge commit
var defaultMessage = "Merge branch `" + this.name + "` into `" + targetBranch.name + "`";
if ( typeof commitOptions !== "object" ) {
var message = commitOptions;
commitOptions = {};
commitOptions.message = (typeof message === "string") ? message : defaultMessage;
} else {
commitOptions.message = commitOptions.message || defaultMessage;
}
commitOptions.type = "mergeCommit";
commitOptions.parentCommit = this.commits.slice( -1 )[ 0 ];
targetBranch.commit( commitOptions );
// Add points to path
var targetCommit = targetBranch.commits.slice( -1 )[ 0 ];
var endOfBranch = {
x: this.offsetX + this.template.commit.spacingX * (targetCommit.showLabel ? 3 : 2) - this.parent.commitOffsetX,
y: this.offsetY + this.template.commit.spacingY * (targetCommit.showLabel ? 3 : 2) - this.parent.commitOffsetY,
type: "join"
};
this.path.push( JSON.parse( JSON.stringify( endOfBranch ) ) ); // Elegant way for cloning an object
var mergeCommit = {
x: targetCommit.x,
y: targetCommit.y,
type: "end"
};
this.path.push( mergeCommit );
endOfBranch.type = "start";
this.path.push( endOfBranch ); // End of branch for future commits
// Auto-render
this.parent.render();
// Checkout on target
this.parent.HEAD = targetBranch;
// Return the main object so we can chain
return this;
};
/**
* Calcul column
*
* @this Branch
**/
Branch.prototype.calculColumn = function () {
var candidates = [];
for ( var i = 0, branch; !!(branch = this.parent.branchs[ i ]); i++ ) {
if ( !branch.isfinish ) {
if ( !( branch.column in candidates ) ) {
candidates[ branch.column ] = 0;
}
candidates[ branch.column ]++;
}
}
this.column = 0;
for ( ; ; this.column++ ) {
if ( !( this.column in candidates ) || candidates[ this.column ] === 0 ) {
break;
}
}
};
// --------------------------------------------------------------------
// ----------------------- Commit ------------------------
// --------------------------------------------------------------------
/**
* Commit
*
* @constructor
*
* @param {Object} options - Commit options
* @param {GitGraph} options.parent - GitGraph constructor
* @param {Number} options.x - Position X (dot)
* @param {Number} options.y - Position Y (dot)
* @param {String} options.color - Master color (dot & message)
* @param {Boolean} options.arrowDisplay - Add a arrow under commit dot
* @param {String} [options.author = this.parent.author] - Author name & email
* @param {String} [options.date] - Date of commit, default is now
* @param {String} [options.detail] - DOM Element of detail part
* @param {String} [options.sha1] - Sha1, default is a random short sha1
* @param {String} [options.dotColor = options.color] - Specific dot color
* @param {Number} [options.dotSize = this.template.commit.dot.size] - Dot size
* @param {Number} [options.dotStrokeWidth = this.template.commit.dot.strokeWidth] - Dot stroke width
* @param {Number} [options.dotStrokeColor = this.template.commit.dot.strokeColor]
* @param {Commit} [options.parentCommit] - Parent commit
* @param {String} [options.message = "He doesn't like George Michael! Boooo!"] - Commit message
* @param {String} [options.messageColor = options.color] - Specific message color
* @param {Boolean} [options.messageDisplay = this.template.commit.message.display] - Commit message policy
* @param {Boolean} [options.messageAuthorDisplay = this.template.commit.message.displayAuthor] - Commit message author policy
* @param {Boolean} [options.messageBranchDisplay = this.template.commit.message.displayBranch] - Commit message author policy
* @param {Boolean} [options.messageHashDisplay = this.template.commit.message.displayHash] - Commit message hash policy
* @param {String} [options.type = ("mergeCommit"|null)] - Type of commit
* @param {commitCallback} [options.onClick] - OnClick event for the commit dot
* @param {Object} [options.representedObject] - Any object which is related to this commit. Can be used in onClick or the formatter. Useful to bind the commit to external objects such as database id etc.
*
* @this Commit
**/
function Commit ( options ) {
// Check integrity
if ( options.parent instanceof GitGraph === false ) {
return;
}
// Options
options = (typeof options === "object") ? options : {};
this.parent = options.parent;
this.template = this.parent.template;
this.context = this.parent.context;
this.branch = options.branch;
this.author = options.author || this.parent.author;
this.date = options.date || new Date().toUTCString();
this.detail = options.detail || null;
this.tag = options.tag || null;
this.tagColor = options.tagColor || options.color;
this.tagFont = options.tagFont || this.template.commit.tag.font;
this.sha1 = options.sha1 || (Math.random( 100 )).toString( 16 ).substring( 3, 10 );
this.message = options.message || "He doesn't like George Michael! Boooo!";
this.arrowDisplay = options.arrowDisplay;
this.messageDisplay = booleanOptionOr( options.messageDisplay, this.template.commit.message.display );
this.messageAuthorDisplay = booleanOptionOr( options.messageAuthorDisplay, this.template.commit.message.displayAuthor );
this.messageBranchDisplay = booleanOptionOr( options.messageBranchDisplay, this.template.commit.message.displayBranch );
this.messageHashDisplay = booleanOptionOr( options.messageHashDisplay, this.template.commit.message.displayHash );
this.messageColor = options.messageColor || options.color;
this.messageFont = options.messageFont || this.template.commit.message.font;
this.dotColor = options.dotColor || options.color;
this.dotSize = options.dotSize || this.template.commit.dot.size;
this.dotStrokeWidth = options.dotStrokeWidth || this.template.commit.dot.strokeWidth;
this.dotStrokeColor = options.dotStrokeColor || this.template.commit.dot.strokeColor || options.color;
this.type = options.type || null;
this.onClick = options.onClick || null;
this.representedObject = options.representedObject || null;
this.parentCommit = options.parentCommit;
this.x = options.x;
this.y = options.y;
this.showLabel = options.showLabel;
this.labelColor = options.labelColor || options.color;
this.labelFont = options.labelFont || this.template.branch.labelFont;
this.parent.commits.push( this );
}
/**
* Render the commit
*
* @this Commit
**/
Commit.prototype.render = function () {
// Label
if ( this.showLabel ) {
drawTextBG( this.context, this.x + this.template.commit.spacingX, this.y + this.template.commit.spacingY, this.branch.name, "black", this.labelColor, this.labelFont, this.template.branch.labelRotation);
}
// Dot
this.context.beginPath();
this.context.arc( this.x, this.y, this.dotSize, 0, 2 * Math.PI, false );
this.context.fillStyle = this.dotColor;
this.context.strokeStyle = this.dotStrokeColor;
this.context.lineWidth = this.dotStrokeWidth;
if ( typeof (this.dotStrokeWidth) === "number" ) {
this.context.stroke();
}
this.context.fill();
this.context.closePath();
// Arrow
if ( this.arrowDisplay && this.parentCommit instanceof Commit ) {
this.arrow();
}
// Detail
if ( this.detail !== null ) {
this.detail.style.left = this.parent.canvas.offsetLeft + (this.parent.columnMax + 1) * this.template.branch.spacingX + 30 + "px";
this.detail.style.top = this.parent.canvas.offsetTop + this.y + 40 + "px";
this.detail.width = 30;
}
this.context.font = this.messageFont;
// Tag
var tagWidth = this.template.commit.tag.spacingX;
if ( this.tag !== null ) {
this.parent.tagNum++;
var textWidth = this.context.measureText(this.tag).width;
if ( this.template.branch.labelRotation !== 0 ) {
var textHeight = getFontHeight(this.tagFont);
drawTextBG( this.context,
this.x - this.dotSize/2,
((this.parent.columnMax + 1) * this.template.commit.tag.spacingY) - this.template.commit.tag.spacingY/2 + (this.parent.tagNum % 2) * textHeight * 1.5,
this.tag, "black", this.tagColor, this.tagFont, 0 );
} else {
drawTextBG( this.context,
((this.parent.columnMax + 1) * this.template.commit.tag.spacingX) - this.template.commit.tag.spacingX/2 + textWidth/2,
this.y - this.dotSize/2,
this.tag, "black", this.tagColor, this.tagFont, 0 );
}
tagWidth = (tagWidth < textWidth) ? textWidth : tagWidth;
}
// Message
if ( this.messageDisplay ) {
var message = this.message;
if ( this.messageHashDisplay ) {
message = this.sha1 + " " + message;
}
if ( this.messageAuthorDisplay ) {
message = message + (this.author ? " - " + this.author : "");
}
if ( this.messageBranchDisplay ) {
message = (this.branch.name ? "[" + this.branch.name + "] " : "") + message;
}
this.context.fillStyle = this.messageColor;
this.context.fillText( message, ((this.parent.columnMax + 1) * this.template.branch.spacingX) + tagWidth, this.y + this.dotSize/2);
}
};
/**
* Render a arrow before commit
*
* @this Commit
**/
Commit.prototype.arrow = function Arrow () {
// Options
var size = this.template.arrow.size;
var color = this.template.arrow.color || this.branch.color;
// Angles calculation
var alpha = Math.atan2(
this.parentCommit.y - this.y,
this.parentCommit.x - this.x
);
// Merge & Fork case
if ( this.type === "mergeCommit" || this === this.branch.commits[ 0 ] /* First commit */ ) {
alpha = Math.atan2(
this.template.branch.spacingY * (this.parentCommit.branch.column - this.branch.column) + this.template.commit.spacingY * (this.showLabel ? 2 : 1),
this.template.branch.spacingX * (this.parentCommit.branch.column - this.branch.column) + this.template.commit.spacingX * (this.showLabel ? 2 : 1)
);
color = this.parentCommit.branch.color;
}
var delta = Math.PI / 7; // Delta between left & right (radian)
// Top
var h = this.template.commit.dot.size + this.template.arrow.offset;
var x1 = h * Math.cos( alpha ) + this.x;
var y1 = h * Math.sin( alpha ) + this.y;
// Bottom left
var x2 = (h + size) * Math.cos( alpha - delta ) + this.x;
var y2 = (h + size) * Math.sin( alpha - delta ) + this.y;
// Bottom center
var x3 = (h + size / 2) * Math.cos( alpha ) + this.x;
var y3 = (h + size / 2) * Math.sin( alpha ) + this.y;
// Bottom right
var x4 = (h + size) * Math.cos( alpha + delta ) + this.x;
var y4 = (h + size) * Math.sin( alpha + delta ) + this.y;
this.context.beginPath();
this.context.fillStyle = color;
this.context.moveTo( x1, y1 ); // Top
this.context.lineTo( x2, y2 ); // Bottom left
this.context.quadraticCurveTo( x3, y3, x4, y4 ); // Bottom center
this.context.lineTo( x4, y4 ); // Bottom right
this.context.fill();
};
// --------------------------------------------------------------------
// ----------------------- Template ------------------------
// --------------------------------------------------------------------
/**
* Template
*
* @constructor
*
* @param {Object} options - Template options
* @param {Array} [options.colors] - Colors scheme: One color for each column
* @param {String} [options.arrow.color] - Arrow color
* @param {Number} [options.arrow.size] - Arrow size
* @param {Number} [options.arrow.offser] - Arrow offset
* @param {String} [options.branch.color] - Branch color
* @param {Number} [options.branch.linewidth] - Branch line width
* @param {String} [options.branch.mergeStyle = ("bezier"|"straight")] - Branch merge style
* @param {Number} [options.branch.spacingX] - Space between branchs
* @param {Number} [options.branch.spacingY] - Space between branchs
* @param {Number} [options.commit.spacingX] - Space between commits
* @param {Number} [options.commit.spacingY] - Space between commits
* @param {Number} [options.commit.widthExtension = 0] - Additional width to be added to the calculated width
* @param {String} [options.commit.color] - Master commit color (dot & message)
* @param {String} [options.commit.dot.color] - Commit dot color
* @param {Number} [options.commit.dot.size] - Commit dot size
* @param {Number} [options.commit.dot.strokewidth] - Commit dot stroke width
* @param {Number} [options.commit.dot.strokeColor] - Commit dot stroke color
* @param {String} [options.commit.message.color] - Commit message color
* @param {Boolean} [options.commit.message.display] - Commit display policy
* @param {Boolean} [options.commit.message.displayAuthor] - Commit message author policy
* @param {Boolean} [options.commit.message.displayBranch] - Commit message branch policy
* @param {Boolean} [options.commit.message.displayHash] - Commit message hash policy
* @param {String} [options.commit.message.font = "normal 12pt Calibri"] - Commit message font
* @param {commitCallback} [options.commit.tooltipHTMLFormatter] - Formatter for the tooltip contents.
*
* @this Template
**/
function Template ( options ) {
// Options
options = (typeof options === "object") ? options : {};
options.branch = options.branch || {};
options.arrow = options.arrow || {};
options.commit = options.commit || {};
options.commit.dot = options.commit.dot || {};
options.commit.tag = options.commit.tag || {};
options.commit.message = options.commit.message || {};
// One color per column
this.colors = options.colors || [ "#6963FF", "#47E8D4", "#6BDB52", "#E84BA5", "#FFA657" ];
// Branch style
this.branch = {};
this.branch.color = options.branch.color || null; // Only one color
this.branch.lineWidth = options.branch.lineWidth || 2;
this.branch.lineDash = options.branch.lineDash || [];
this.branch.showLabel = options.branch.showLabel || false;
this.branch.labelColor = options.branch.labelColor || null;
this.branch.labelFont = options.branch.labelFont || "normal 8pt Calibri";
this.branch.labelRotation = options.branch.labelRotation || 0;
// Merge style = "bezier" | "straight"
this.branch.mergeStyle = options.branch.mergeStyle || "bezier";
// Space between branchs
this.branch.spacingX = (typeof options.branch.spacingX === "number") ? options.branch.spacingX : 20;
this.branch.spacingY = options.branch.spacingY || 0;
// Arrow style
this.arrow = {};
this.arrow.size = options.arrow.size || null;
this.arrow.color = options.arrow.color || null;
this.arrow.active = typeof (this.arrow.size) === "number";
this.arrow.offset = options.arrow.offset || 2;
// Commit style
this.commit = {};
this.commit.spacingX = options.commit.spacingX || 0;
this.commit.spacingY = (typeof options.commit.spacingY === "number") ? options.commit.spacingY : 25;
this.commit.widthExtension = (typeof options.commit.widthExtension === "number") ? options.commit.widthExtension : 0;
this.commit.tooltipHTMLFormatter = options.commit.tooltipHTMLFormatter || null;
// Only one color, if null message takes branch color (full commit)
this.commit.color = options.commit.color || null;
this.commit.dot = {};
// Only one color, if null message takes branch color (only dot)
this.commit.dot.color = options.commit.dot.color || null;
this.commit.dot.size = options.commit.dot.size || 3;
this.commit.dot.strokeWidth = options.commit.dot.strokeWidth || null;
this.commit.dot.strokeColor = options.commit.dot.strokeColor || null;
this.commit.tag = {};
this.commit.tag.color = options.commit.tag.color || this.commit.dot.color;
this.commit.tag.font = options.commit.tag.font || options.commit.message.font || "normal 10pt Calibri";
this.commit.tag.spacingX = this.branch.spacingX;
this.commit.tag.spacingY = this.commit.spacingY;
this.commit.message = {};
this.commit.message.display = booleanOptionOr( options.commit.message.display, true );
this.commit.message.displayAuthor = booleanOptionOr( options.commit.message.displayAuthor, true );
this.commit.message.displayBranch = booleanOptionOr( options.commit.message.displayBranch, true );
this.commit.message.displayHash = booleanOptionOr( options.commit.message.displayHash, true );
// Only one color, if null message takes commit color (only message)
this.commit.message.color = options.commit.message.color || null;
this.commit.message.font = options.commit.message.font || "normal 12pt Calibri";
}
/**
* Get a default template from library
*
* @param {String} name - Template name
*
* @return {Template} [template] - Template if exist
**/
Template.prototype.get = function ( name ) {
var template = {};
switch ( name ) {
case "blackarrow":
template = {
branch: {
color: "#000000",
lineWidth: 4,
spacingX: 50,
mergeStyle: "straight"
},
commit: {
spacingY: -60,
dot: {
size: 12,
strokeColor: "#000000",
strokeWidth: 7
},
message: {
color: "black"
}
},
arrow: {
size: 16,
offset: 2.5
}
};
break;
case "metro":
/* falls through */
default:
template = {
colors: [ "#979797", "#008fb5", "#f1c109" ],
branch: {
lineWidth: 10,
spacingX: 50
},
commit: {
spacingY: -80,
dot: {
size: 14
},
message: {
font: "normal 14pt Arial"
}
}
};
break;
}
return new Template( template );
};
// --------------------------------------------------------------------
// ----------------------- Utilities -----------------------
// --------------------------------------------------------------------
var getFontHeight = function ( font ) {
var body = document.getElementsByTagName("body")[0];
var dummy = document.createElement("div");
var dummyText = document.createTextNode("Mg");
dummy.appendChild(dummyText);
dummy.setAttribute("style", "font: " + font + ";");
body.appendChild(dummy);
var result = dummy.offsetHeight;
body.removeChild(dummy);
return result;
};
function booleanOptionOr ( booleanOption, defaultOption ) {
return (typeof booleanOption === "boolean") ? booleanOption : defaultOption;
}
function drawTextBG ( context, x, y, text, fgcolor, bgcolor, font, angle ) {
context.save();
context.translate(x, y);
context.rotate(angle*(Math.PI/180));
context.textAlign = "center";
context.font = font;
var width = context.measureText(text).width;
var height = getFontHeight(font);
context.beginPath();
context.rect(-(width/2)-4, -(height/2)+2, width+8, height+2);
context.fillStyle = bgcolor;
context.fill();
context.lineWidth = 2;
context.strokeStyle = "black";
context.stroke();
context.fillStyle = fgcolor;
context.fillText(text, 0, height/2);
context.restore();
}
// Expose GitGraph object
window.GitGraph = GitGraph;
window.GitGraph.Branch = Branch;
window.GitGraph.Commit = Commit;
window.GitGraph.Template = Template;
})();
| froala/cdnjs | ajax/libs/gitgraph.js/1.1.0/gitgraph.js | JavaScript | mit | 42,437 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Tests\Test\Constraint;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Test\Constraint\ResponseHasCookie;
class ResponseHasCookieTest extends TestCase
{
public function testConstraint(): void
{
$response = new Response();
$response->headers->setCookie(Cookie::create('foo', 'bar'));
$constraint = new ResponseHasCookie('foo');
$this->assertTrue($constraint->evaluate($response, '', true));
$constraint = new ResponseHasCookie('bar');
$this->assertFalse($constraint->evaluate($response, '', true));
try {
$constraint->evaluate($response);
} catch (ExpectationFailedException $e) {
$this->assertEquals("Failed asserting that the Response has cookie \"bar\".\n", TestFailure::exceptionToString($e));
return;
}
$this->fail();
}
}
| dmaicher/symfony | src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseHasCookieTest.php | PHP | mit | 1,338 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : factory(global.frzr = {});
})(this, function (exports) {
'use strict';
function Emitter() {
var self = this;
var isEmitter = self instanceof Emitter;
if (!isEmitter) {
return new Emitter();
}
self.listeners = {};
return self;
}
var emitterProto = Emitter.prototype;
emitterProto.on = on;
emitterProto.off = off;
emitterProto.trigger = trigger;
function on(name, cb, ctx) {
var self = this;
var listeners = self.listeners[name] || (self.listeners[name] = []);
listeners.push({
cb: cb,
ctx: ctx
});
return self;
}
function trigger(name) {
var self = this;
var args = slice(arguments, 1);
var listeners = self.listeners[name];
if (!listeners) {
return self;
}
each(listeners, function (listener) {
listener.cb.apply(listener.ctx || self, args);
});
return self;
}
function off(name, cb) {
var self = this;
var listeners;
if (cb) {
listeners = self.listeners[name];
if (!listeners) {
return self;
}
self.listeners = filter(listeners, function (listener) {
return listener.cb === cb;
});
return self;
}
if (name) {
delete listeners[name];
return self;
}
self.listeners = {};
return self;
}
exports.Emitter = Emitter;
function View(type) {
var self = this;
var isView = self instanceof View;
if (!isView) {
return new View(type);
}
View['super'].call(this);
self.data = {};
self.$el = document.createElement(type || 'div');
}
inherit(View, Emitter);
var viewProto = View.prototype;
viewProto.mount = lib_view__mount;
viewProto.unmount = unmount;
viewProto.text = text;
viewProto.html = html;
viewProto.addClass = addClass;
viewProto.removeClass = removeClass;
viewProto.reset = lib_view__reset;
viewProto.destroy = destroy;
View.extend = lib_view__extend;
function lib_view__mount(root) {
var self = this;
self.root = root;
if (root instanceof View) {
root = root.$el;
}
root.appendChild(self.$el);
return self;
}
function unmount() {
var self = this;
var root = self.root;
if (!root) {
return;
}
if (root instanceof View) {
root = root.$el;
}
root.removeChild(self.$el);
return self;
}
function text(text) {
var self = this;
self.$el.textContent = text;
return self;
}
function html(html) {
var self = this;
self.$el.innerHTML = html;
return self;
}
function addClass(className) {
var self = this;
self.$el.classList.add(className);
return self;
}
function removeClass(className) {
var self = this;
self.$el.classList.remove(className);
return self;
}
function lib_view__reset(data) {
var self = this;
self.trigger('update', self, data, self.data);
self.data = data;
return self;
}
function destroy() {
var self = this;
self.trigger('destroy', self);
self.off();
self.unmount();
return self;
}
function lib_view__extend(extendedType) {
var emitter = new Emitter();
var classes = [];
var classLookup = {};
var params = {};
function ExtendedView(type) {
var view = new View(type || extendedType);
view.listeners = emitter.listeners;
each(classes, function (className) {
view.addClass(className);
});
if (params.root) {
view.mount(params.root);
}
view.trigger('init', view);
return view;
}
ExtendedView.mount = function mount(root) {
params.root = root;
return ExtendedView;
};
ExtendedView.unmount = function mount(_root) {
delete params.root;
return ExtendedView;
};
ExtendedView.addClass = function addClass(className) {
if (classLookup[className]) {
return ExtendedView;
}
classes.push(className);
classLookup[className] = true;
return ExtendedView;
};
ExtendedView.removeClass = function addClass(className) {
if (classLookup[className]) {
classes = filter(classes, function (_className) {
return _className !== className;
});
delete classLookup[className];
}
return ExtendedView;
};
ExtendedView.on = function on(name, cb, ctx) {
emitter.on(name, cb, ctx);
return ExtendedView;
};
ExtendedView.off = function off(name, cb, ctx) {
emitter.off(name, cb, ctx);
return ExtendedView;
};
return ExtendedView;
}
exports.View = View;
function ViewList(view, idAttribute) {
var self = this;
var isViewList = self instanceof ViewList;
if (!isViewList) {
return new ViewList(view, idAttribute);
}
self.idAttribute = idAttribute;
self.View = view || View;
self.views = [];
self.lookup = {};
return self;
}
inherit(ViewList, Emitter);
var ViewListProto = ViewList.prototype;
ViewListProto.mount = viewlist__mount;
ViewListProto.reset = viewlist__reset;
ViewList.extend = viewlist__extend;
function viewlist__mount(root) {
var self = this;
root = root || self.root;
if (!root) {
return;
}
if (root instanceof View) {
root = root.$el;
}
// Update items
var traverse = root.firstChild;
each(self.views, function (view, i) {
if (traverse === view.$el) {
traverse = traverse.nextSibling;
return;
}
if (traverse) {
root.insertBefore(view.$el, traverse);
} else {
root.appendChild(view.$el);
}
});
var next;
while (traverse) {
next = traverse.nextSibling;
root.removeChild(traverse);
traverse = next;
}
self.root = root;
return self;
}
function viewlist__reset(items) {
var self = this;
var idAttribute = self.idAttribute;
var views;
if (idAttribute == null) {
views = reduce(items, new Array(items.length), function (init, item, i) {
var view = self.views[i];
if (!view) {
view = new self.View();
}
view.reset(item);
init[i] = view;
return init;
});
self.views = views;
self.mount();
return self;
}
var lookup = {};
views = reduce(items, [], function (init, item, i) {
var id = item[idAttribute];
var currentView = self.lookup[id];
if (!currentView) {
currentView = new self.View();
}
currentView.reset(item);
init[i] = lookup[id] = currentView;
return init;
});
each(self.views, function (view, i) {
var id = view[idAttribute];
if (!lookup[id]) {
view.destroy();
delete lookup[id];
}
});
self.views = views;
self.lookup = lookup;
self.mount();
return self;
}
function viewlist__extend(extendedIdAttribute, extendedView) {
var emitter = new Emitter();
var params = {};
function ExtendedViewList(idAttribute, view) {
var ViewList = new ViewList(idAttribute || extendedIdAttribute, view || extendedView);
ViewList.listeners = emitter.listeners;
if (params.root) {
ViewList.mount(params.root);
}
return ViewList;
}
ExtendedViewList.mount = function (root) {
params.root = root;
return ExtendedViewList;
};
ExtendedViewList.unmount = function () {
delete params.root;
return ExtendedViewList;
};
ExtendedViewList.on = function (name, cb, ctx) {
emitter.on(name, cb, ctx);
return ExtendedViewList;
};
return ExtendedViewList;
}
exports.ViewList = ViewList;
function each(array, iterator) {
for (var i = 0, len = array.length; i < len; i++) {
iterator(array[i], i);
}
}
function filter(array, iterator) {
var results = [];
each(array, function (item, i) {
if (iterator(item, i)) {
results.push(item);
}
});
return results;
}
function slice(array, start, end) {
var len = array.length;
if (start == null) {
start = 0;
}
if (end == null) {
end = len;
}
if (start < 0) {
start = len + start;
}
if (end < 0) {
end = len + end;
}
len = end - start;
var results = new Array(len);
for (var i = 0; i < len; i++) {
results[i] = array[start + i];
}
return results;
}
function map(array, iterator) {
var len = array.length;
var results = new Array(len);
for (var i = 0; i < len; i++) {
results[i] = iterator(array[i], i);
}
return results;
}
function timesMap(len, iterator) {
var results = new Array(len);
for (var i = 0; i < len; i++) {
results[i] = iterator(i);
}
return results;
}
function reduce(array, init, iterator) {
each(array, function (item, i) {
init = iterator(init, item, i);
});
return init;
}
exports.each = each;
exports.filter = filter;
exports.map = map;
exports.slice = slice;
exports.timesMap = timesMap;
exports.reduce = reduce;
function inherit(target, superClass) {
var prototype = superClass && superClass.prototype || null;
target['super'] = superClass;
target.prototype = Object.create(prototype, {
constructor: {
configurable: true,
value: target,
writable: true
}
});
return target.prototype;
}
exports.inherit = inherit;
function forIn(object, iterator) {
var key;
for (key in object) {
iterator(object[key], key);
}
}
exports.forIn = forIn;
});
| sashberd/cdnjs | ajax/libs/frzr/0.3.1/frzr.js | JavaScript | mit | 9,908 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// the subtype here that contains a Canonical type is Node<NodeStruct<NodeSys<a[]>>>
using System;
public class Node<a>
{
public static Node<a> leaf;
static Node()
{
leaf = new Node<a>();
Console.WriteLine("Node<A>'s .cctor ran, where A was {0}.", typeof(a));
Console.WriteLine("Leaf: {0}", leaf);
}
}
public struct NodeStruct<a> { }
public class NodeSys<a> { }
public class SystemMap<a>
{
public Node <NodeStruct<NodeSys<a[]>>> root;
public SystemMap(a x)
{
Console.WriteLine("Accessing a static from Node<NodeStruct<NodeSys<a[]>>>...");
this.root = Node<NodeStruct<NodeSys<a[]>>>.leaf;
}
public bool Eval()
{
Console.WriteLine("Read a static from Node<NodeStruct<NodeSys<a[]>>>. Got: {0}",
(root == null) ? "<null>" : root.ToString());
if (root == null)
return false;
else
return true;
}
}
class Test
{
static int Main ()
{
Console.WriteLine("-------------------------------------------------------------------");
SystemMap<Int32> y1 = new SystemMap<Int32> (5);
Console.WriteLine("-------------------------------------------------------------------");
SystemMap<String> y2 = new SystemMap<String> ("S");
Console.WriteLine("-------------------------------------------------------------------");
SystemMap<Object> y3 = new SystemMap<Object> ("S");
Console.WriteLine("-------------------------------------------------------------------");
if (y1.Eval() && y2.Eval() && y3.Eval() )
{
Console.WriteLine("PASS");
return 100;
}
else
{
Console.WriteLine("FAIL");
return 101;
}
}
}
| xtypebee/coreclr | tests/src/Loader/regressions/classloader-generics/StaticsProblem5.cs | C# | mit | 1,815 |
/*! ally.js - v1.1.1 - http://allyjs.io/ - MIT License */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.ally=e()}}(function(){var e;return function t(e,n,o){function r(a,i){if(!n[a]){if(!e[a]){var l="function"==typeof require&&require;if(!i&&l)return l(a,!0);if(u)return u(a,!0);var s=new Error("Cannot find module '"+a+"'");throw s.code="MODULE_NOT_FOUND",s}var d=n[a]={exports:{}};e[a][0].call(d.exports,function(t){var n=e[a][1][t];return r(n?n:t)},d,d.exports,t,e,n,o)}return n[a].exports}for(var u="function"==typeof require&&require,a=0;a<o.length;a++)r(o[a]);return r}({1:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./element/_element"),u=o(r),a=e("./event/_event"),i=o(a),l=e("./fix/_fix"),s=o(l),d=e("./get/_get"),c=o(d),f=e("./is/_is"),m=o(f),p=e("./maintain/_maintain"),b=o(p),v=e("./map/_map"),h=o(v),g=e("./observe/_observe"),y=o(g),x=e("./query/_query"),_=o(x),w=e("./style/_style"),M=o(w),E=e("./when/_when"),O=o(E),S=e("./version"),P=o(S),A="undefined"!=typeof window&&window.ally;n["default"]={element:u["default"],event:i["default"],fix:s["default"],get:c["default"],is:m["default"],maintain:b["default"],map:h["default"],observe:y["default"],query:_["default"],style:M["default"],when:O["default"],version:P["default"],noConflict:function(){return"undefined"!=typeof window&&window.ally===this&&(window.ally=A),this}},t.exports=n["default"]},{"./element/_element":2,"./event/_event":4,"./fix/_fix":7,"./get/_get":11,"./is/_is":20,"./maintain/_maintain":38,"./map/_map":42,"./observe/_observe":45,"./query/_query":52,"./style/_style":66,"./version":129,"./when/_when":130}],2:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./disabled"),u=o(r);n["default"]={disabled:u["default"]},t.exports=n["default"]},{"./disabled":3}],3:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){_["default"].warn("trying to focus inert element",this)}function u(e,t){if(t){var n=b["default"](e);y["default"]({element:e,attribute:"tabindex",temporaryValue:"-1",saveValue:null!==n?n:""})}else y["default"]({element:e,attribute:"tabindex"})}function a(e,t){var n=e.nodeName.toLowerCase();if("video"===n||"audio"===n)if(t)e.hasAttribute("controls")&&(e.setAttribute("data-inert-controls",""),e.removeAttribute("controls"));else{var o=e.hasAttribute("data-inert-controls");o&&(e.removeAttribute("data-inert-controls"),e.setAttribute("controls",""))}}function i(e,t){var n=e.nodeName.toLowerCase();("svg"===n||e.ownerSVGElement)&&y["default"]({element:e,attribute:"focusable",temporaryValue:t?"false":void 0})}function l(e,t){y["default"]({element:e,attribute:"aria-disabled",temporaryValue:t?"true":void 0})}function s(e,t){t?e.focus=r:delete e.focus}function d(e,t){if(t){var n=e.style.pointerEvents||"";e.setAttribute("data-inert-pointer-events",n),e.style.pointerEvents="none"}else{var n=e.getAttribute("data-inert-pointer-events");e.removeAttribute("data-inert-pointer-events"),e.style.pointerEvents=n}}function c(e,t){l(e,t),u(e,t),s(e,t),d(e,t),a(e,t),i(e,t),t?e.setAttribute("data-ally-disabled","true"):e.removeAttribute("data-ally-disabled")}Object.defineProperty(n,"__esModule",{value:!0});var f=e("../util/context-to-element"),m=o(f),p=e("../util/tabindex-value"),b=o(p),v=e("../is/native-disabled-supported"),h=o(v),g=e("../util/toggle-attribute-value"),y=o(g),x=e("../util/logger"),_=o(x);n["default"]=function(e,t){var n=m["default"]({label:"element/disabled",context:e});t=Boolean(t);var o=n.hasAttribute("data-ally-disabled"),r=1===arguments.length;return h["default"](n)?r?n.disabled:(n.disabled=t,n):r?o:o===t?n:(c(n,t),n)},t.exports=n["default"]},{"../is/native-disabled-supported":28,"../util/context-to-element":112,"../util/logger":120,"../util/tabindex-value":126,"../util/toggle-attribute-value":127}],4:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./active-element"),u=o(r),a=e("./shadow-focus"),i=o(a);n["default"]={activeElement:u["default"],shadowFocus:i["default"]},t.exports=n["default"]},{"./active-element":5,"./shadow-focus":6}],5:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){if(document.activeElement){if(document.activeElement!==c){var e=new l["default"]("active-element",{bubbles:!1,cancelable:!1,detail:{focus:document.activeElement,blur:c}});document.dispatchEvent(e),c=document.activeElement}}else document.body.focus();f!==!1&&(f=requestAnimationFrame(r))}function u(){f=!0,c=document.activeElement,r()}function a(){cancelAnimationFrame(f),f=!1}Object.defineProperty(n,"__esModule",{value:!0}),e("../prototype/window.requestanimationframe");var i=e("../prototype/window.customevent"),l=o(i),s=e("../util/decorate-service"),d=o(s),c=void 0,f=void 0;n["default"]=d["default"]({engage:u,disengage:a}),t.exports=n["default"]},{"../prototype/window.customevent":50,"../prototype/window.requestanimationframe":51,"../util/decorate-service":114}],6:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../get/active-elements"),u=o(r),a=e("../util/decorate-service"),i=o(a),l=void 0,s=void 0;"undefined"!=typeof document&&document.documentElement.createShadowRoot?!function(){var e=void 0,t=void 0,n=void 0,o=void 0,r=function(){o(),(window.clearImmediate||window.clearTimeout)(e),e=(window.setImmediate||window.setTimeout)(function(){n()})},a=function(e){e.addEventListener("blur",r,!0),t=e};o=function(){t&&t.removeEventListener("blur",r,!0),t=null},n=function(){var e=u["default"]();if(1===e.length)return void o();a(e[0]);var t=new CustomEvent("shadow-focus",{bubbles:!1,cancelable:!1,detail:{elements:e,active:e[0],hosts:e.slice(1)}});document.dispatchEvent(t)};var i=function(){(window.clearImmediate||window.clearTimeout)(e),n()};l=function(){document.addEventListener("focus",i,!0)},s=function(){(window.clearImmediate||window.clearTimeout)(e),t&&t.removeEventListener("blur",r,!0),document.removeEventListener("focus",i,!0)}}():l=s=function(){},n["default"]=i["default"]({engage:l,disengage:s}),t.exports=n["default"]},{"../get/active-elements":12,"../util/decorate-service":114}],7:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./pointer-focus-children"),u=o(r),a=e("./pointer-focus-input"),i=o(a),l=e("./pointer-focus-parent"),s=o(l);n["default"]={pointerFocusChildren:u["default"],pointerFocusInput:i["default"],pointerFocusParent:s["default"]},t.exports=n["default"]},{"./pointer-focus-children":8,"./pointer-focus-input":9,"./pointer-focus-parent":10}],8:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../get/focus-target"),u=o(r),a=e("../util/decorate-context"),i=o(a),l=e("../util/platform"),s=o(l),d=void 0,c=void 0,f=s["default"].is.TRIDENT&&(s["default"].is.IE10||s["default"].is.IE11);f?!function(){var e=function(e){var t=u["default"]({context:e.target,except:{flexbox:!0,scrollable:!0}});if(t&&t!==e.target){window.setImmediate(function(){t.focus()});var n=[].map.call(t.children,function(e){var t=e.style.visibility||"",n=e.style.transition||"";return e.style.visibility="hidden",e.style.transition="none",[e,t,n]});window.setImmediate(function(){n.forEach(function(e){e[0].style.visibility=e[1],e[0].style.transition=e[2]})})}};d=function(t){t.addEventListener("mousedown",e,!0)},c=function(t){t.removeEventListener("mousedown",e,!0)}}():d=function(){},n["default"]=i["default"]({engage:d,disengage:c}),t.exports=n["default"]},{"../get/focus-target":15,"../util/decorate-context":113,"../util/platform":123}],9:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../prototype/element.prototype.matches"),u=o(r),a=e("../get/focus-target"),i=o(a),l=e("../util/decorate-context"),s=o(l),d=e("../util/get-window"),c=o(d),f=e("../util/platform"),m=o(f),p=void 0,b=void 0,v=m["default"].is.OSX&&(m["default"].is.GECKO||m["default"].is.WEBKIT);v?!function(){var e=function(e){var t=c["default"](e.target);if(u["default"](t),!e.defaultPrevented&&e.target.matches("input, button, button *")){var n=i["default"]({context:e.target});(window.setImmediate||window.setTimeout)(function(){n.focus()})}},t=function(e){var t=c["default"](e.target);if(u["default"](t),!e.defaultPrevented&&e.target.matches("label, label *")){var n=i["default"]({context:e.target});n&&n.focus()}};p=function(n){n.addEventListener("mousedown",e,!1),n.addEventListener("mouseup",t,!1)},b=function(n){n.removeEventListener("mousedown",e,!1),n.removeEventListener("mouseup",t,!1)}}():p=function(){},n["default"]=s["default"]({engage:p,disengage:b}),t.exports=n["default"]},{"../get/focus-target":15,"../prototype/element.prototype.matches":48,"../util/decorate-context":113,"../util/get-window":118,"../util/platform":123}],10:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../get/focus-target"),u=o(r),a=e("../is/valid-tabindex"),i=o(a),l=e("../util/decorate-context"),s=o(l),d=e("../util/platform"),c=o(d),f=void 0,m=void 0,p=c["default"].is.WEBKIT;p?!function(){var e=function(e){var t=u["default"]({context:e.target});!t||t.hasAttribute("tabindex")&&i["default"](t)||(t.setAttribute("tabindex",0),(window.setImmediate||window.setTimeout)(function(){t.removeAttribute("tabindex")},0))};f=function(t){t.addEventListener("mousedown",e,!0),t.addEventListener("touchstart",e,!0)},m=function(t){t.removeEventListener("mousedown",e,!0),t.removeEventListener("touchstart",e,!0)}}():f=function(){},n["default"]=s["default"]({engage:f,disengage:m}),t.exports=n["default"]},{"../get/focus-target":15,"../is/valid-tabindex":35,"../util/decorate-context":113,"../util/platform":123}],11:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./active-elements"),u=o(r),a=e("./focus-redirect-target"),i=o(a),l=e("./focus-target"),s=o(l),d=e("./insignificant-branches"),c=o(d),f=e("./parents"),m=o(f),p=e("./shadow-host-parents"),b=o(p),v=e("./shadow-host"),h=o(v);n["default"]={activeElements:u["default"],focusRedirectTarget:i["default"],focusTarget:s["default"],insignificantBranches:c["default"],parents:m["default"],shadowHostParents:b["default"],shadowHost:h["default"]},t.exports=n["default"]},{"./active-elements":12,"./focus-redirect-target":13,"./focus-target":15,"./insignificant-branches":16,"./parents":17,"./shadow-host":19,"./shadow-host-parents":18}],12:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){for(var e=[document.activeElement];e[0]&&e[0].shadowRoot;)e.unshift(e[0].shadowRoot.activeElement);return e}function u(){var e=s["default"]({context:document.activeElement});return[document.activeElement].concat(e)}Object.defineProperty(n,"__esModule",{value:!0});var a=e("../is/shadowed"),i=o(a),l=e("./shadow-host-parents"),s=o(l);n["default"]=function(){return null===document.activeElement&&document.body.focus(),i["default"](document.activeElement)?u():r()},t.exports=n["default"]},{"../is/shadowed":31,"./shadow-host-parents":18}],13:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.nodeName.toLowerCase();return"input"===t||"textarea"===t||"select"===t||"button"===t}function u(e,t){var n=e.getAttribute("for");return n?t.getElementById(n):e.querySelector("input, select, textarea")}function a(e){var t=e.parentNode,n=m["default"]({context:t,strategy:"strict"});return n.filter(r)[0]||null}function i(e,t){var n=b["default"]({context:t.body,strategy:"strict"});if(!n.length)return null;var o=_["default"]({list:n,elements:[e]}),r=o.indexOf(e);return r===o.length-1?null:o[r+1]}function l(e,t){if(!O.canFocusRedirectLegend)return null;var n=e.parentNode;return"fieldset"!==n.nodeName.toLowerCase()?null:"tabbable"===O.canFocusRedirectLegend?i(e,t):a(e,t)}function s(e){if(!O.canFocusRedirectImgUsemap)return null;var t=w.getMapOfImage(e);return t&&t.querySelector("area")||null}Object.defineProperty(n,"__esModule",{value:!0});var d=e("../is/focusable"),c=o(d),f=e("../query/focusable"),m=o(f),p=e("../query/tabbable"),b=o(p),v=e("../util/context-to-element"),h=o(v),g=e("../util/get-document"),y=o(g),x=e("../util/merge-dom-order"),_=o(x),w=e("../util/image-map"),M=e("./focus-redirect-target.supports"),E=o(M),O=void 0;n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.skipFocusable;O||(O=E["default"]());var o=h["default"]({label:"get/focus-redirect-target",context:t});if(!n&&c["default"](o))return null;var r=o.nodeName.toLowerCase(),a=y["default"](o);return"label"===r?u(o,a):"legend"===r?l(o,a):"img"===r?s(o,a):null},t.exports=n["default"]},{"../is/focusable":26,"../query/focusable":54,"../query/tabbable":58,"../util/context-to-element":112,"../util/get-document":116,"../util/image-map":119,"../util/merge-dom-order":121,"./focus-redirect-target.supports":14}],14:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/focus-redirect-img-usemap"),i=o(a),l=e("../supports/focus-redirect-legend"),s=o(l);n["default"]=u["default"](function(){return{canFocusRedirectImgUsemap:i["default"](),canFocusRedirectLegend:s["default"]()}}),t.exports=n["default"]},{"../supports/focus-redirect-img-usemap":91,"../supports/focus-redirect-legend":92,"../supports/memorize-result":107}],15:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./focus-redirect-target"),u=o(r),a=e("../get/parents"),i=o(a),l=e("../is/focusable"),s=o(l),d=e("../util/context-to-element"),c=o(d);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.except,o=c["default"]({label:"get/focus-target",context:t}),r=null,a=function(e){var t=s["default"].rules({context:e,except:n});return t?(r=e,!0):(r=u["default"]({context:e,skipFocusable:!0}),Boolean(r))};return a(o)?r:(i["default"]({context:o}).slice(1).some(a),r)},t.exports=n["default"]},{"../get/parents":17,"../is/focusable":26,"../util/context-to-element":112,"./focus-redirect-target":13}],16:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.context,n=e.filter,o=function(e){var t=s.getParentComparator({parent:e});return n.some(t)},r=[],u=function(e){return n.some(function(t){return e===t})?NodeFilter.FILTER_REJECT:o(e)?NodeFilter.FILTER_ACCEPT:(r.push(e),NodeFilter.FILTER_REJECT)};u.acceptNode=u;for(var a=c["default"](t),i=a.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,u,!1);i.nextNode(););return r}Object.defineProperty(n,"__esModule",{value:!0});var u=e("../util/context-to-element"),a=o(u),i=e("../util/node-array"),l=o(i),s=e("../util/compare-position"),d=e("../util/get-document"),c=o(d);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.filter;if(t=a["default"]({label:"get/insignificant-branches",defaultToDocument:!0,context:t}),n=l["default"](n),!n.length)throw new TypeError("get/insignificant-branches requires valid options.filter");return r({context:t,filter:n})},t.exports=n["default"]},{"../util/compare-position":111,"../util/context-to-element":112,"../util/get-document":116,"../util/node-array":122}],17:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r);n["default"]=function(){for(var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=[],o=u["default"]({label:"get/parents",context:t});o;)n.push(o),o=o.parentNode,o&&o.nodeType!==Node.ELEMENT_NODE&&(o=null);return n},t.exports=n["default"]},{"../util/context-to-element":112}],18:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./shadow-host"),u=o(r),a=e("../util/context-to-element"),i=o(a);n["default"]=function(){for(var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=[],o=i["default"]({label:"get/shadow-host-parents",context:t});o&&(o=u["default"]({context:o}));)n.push(o);return n},t.exports=n["default"]},{"../util/context-to-element":112,"./shadow-host":19}],19:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r);n["default"]=function(){for(var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=u["default"]({label:"get/shadow-host",context:t}),o=null;n;)o=n,n=n.parentNode;return o.nodeType===o.DOCUMENT_FRAGMENT_NODE&&o.host?o.host:null},t.exports=n["default"]},{"../util/context-to-element":112}],20:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./active-element"),u=o(r),a=e("./disabled"),i=o(a),l=e("./focus-relevant"),s=o(l),d=e("./focusable"),c=o(d),f=e("./only-tabbable"),m=o(f),p=e("./shadowed"),b=o(p),v=e("./tabbable"),h=o(v),g=e("./valid-area"),y=o(g),x=e("./valid-tabindex"),_=o(x),w=e("./visible"),M=o(w);n["default"]={activeElement:u["default"],disabled:i["default"],focusRelevant:s["default"],focusable:c["default"],onlyTabbable:m["default"],shadowed:b["default"],tabbable:h["default"],validArea:y["default"],validTabindex:_["default"],visible:M["default"]},t.exports=n["default"]},{"./active-element":21,"./disabled":22,"./focus-relevant":24,"./focusable":26,"./only-tabbable":30,"./shadowed":31,"./tabbable":32,"./valid-area":33,"./valid-tabindex":35,"./visible":37}],21:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r),a=e("../get/shadow-host"),i=o(a),l=e("../util/get-document"),s=o(l);n["default"]=function(e){var t=u["default"]({label:"is/active-element",resolveDocument:!0,context:e}),n=s["default"](t);if(n.activeElement===t)return!0;var o=i["default"]({context:t});return o&&o.shadowRoot.activeElement===t?!0:!1},t.exports=n["default"]},{"../get/shadow-host":19,"../util/context-to-element":112,"../util/get-document":116}],22:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.nodeName.toLowerCase();return"fieldset"===t&&e.disabled}function u(e){var t=e.nodeName.toLowerCase();return"form"===t&&e.disabled}Object.defineProperty(n,"__esModule",{value:!0});var a=e("../util/context-to-element"),i=o(a),l=e("../get/parents"),s=o(l),d=e("./native-disabled-supported"),c=o(d),f=e("./disabled.supports"),m=o(f),p=void 0;n["default"]=function(e){p||(p=m["default"]());var t=i["default"]({label:"is/disabled",context:e});if(t.hasAttribute("data-ally-disabled"))return!0;if(!c["default"](t))return!1;if(t.disabled)return!0;var n=s["default"]({context:t});return n.some(r)?!0:!p.canFocusDisabledForm&&n.some(u)?!0:!1},t.exports=n["default"]},{"../get/parents":17,"../util/context-to-element":112,"./disabled.supports":23,"./native-disabled-supported":28}],23:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/focus-form-disabled"),i=o(a);n["default"]=u["default"](function(){return{canFocusDisabledForm:i["default"]()}}),t.exports=n["default"]},{"../supports/focus-form-disabled":81,"../supports/memorize-result":107}],24:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.except,o=void 0===n?{flexbox:!1,scrollable:!1,shadow:!1}:n;x||(x=y["default"]());var r=f["default"]({label:"is/focus-relevant",resolveDocument:!0,context:t});if(!o.shadow&&r.shadowRoot)return!0;var u=r.nodeName.toLowerCase();if("input"===u&&"hidden"===r.type)return!1;if("input"===u||"select"===u||"button"===u||"textarea"===u)return!0;if("legend"===u&&x.canFocusRedirectLegend)return!0;if("label"===u)return!0;if("area"===u)return!0;if("a"===u&&r.hasAttribute("href"))return!0;if("object"===u&&r.hasAttribute("usemap"))return!1;if("object"===u){var i=r.getAttribute("type");if(!x.canFocusObjectSvg&&"image/svg+xml"===i)return!1;if(!x.canFocusObjectSwf&&"application/x-shockwave-flash"===i)return!1}if("iframe"===u||"object"===u)return!0;if("embed"===u||"keygen"===u)return!0;if(r.hasAttribute("contenteditable"))return!0;if("audio"===u&&(x.canFocusAudioWithoutControls||r.hasAttribute("controls")))return!0;if("video"===u&&(x.canFocusVideoWithoutControls||r.hasAttribute("controls")))return!0;if(x.canFocusSummary&&"summary"===u)return!0;var s=v["default"](r);if("img"===u&&r.hasAttribute("usemap"))return s&&x.canFocusImgUsemapTabindex||x.canFocusRedirectImgUsemap;if(x.canFocusTable&&("table"===u||"td"===u))return!0;if(x.canFocusFieldset&&"fieldset"===u)return!0;var c=r.getAttribute("focusable");if("svg"===u)return s||x.canFocusSvg||Boolean(x.canFocusSvgFocusableAttribute&&c&&"true"===c);var m=p["default"](r);if(a["default"](m),r.matches("svg a")&&r.hasAttribute("xlink:href"))return!0;if(l["default"](m),x.canFocusSvgFocusableAttribute&&r.ownerSVGElement)return Boolean(c&&"true"===c);if(s)return!0;var b=window.getComputedStyle(r,null);if(h.isUserModifyWritable(b))return!0;if(x.canFocusImgIsmap&&"img"===u&&r.hasAttribute("ismap")){var g=d["default"]({context:r}).some(function(e){return"a"===e.nodeName.toLowerCase()&&e.hasAttribute("href")});if(g)return!0}if(!o.scrollable&&x.canFocusScrollContainer)if(x.canFocusScrollContainerWithoutOverflow){if(h.isScrollableContainer(r,u))return!0}else if(h.hasCssOverflowScroll(b))return!0;if(!o.flexbox&&x.canFocusFlexboxContainer&&h.hasCssDisplayFlex(b))return!0;var _=r.parentElement;if(!o.scrollable&&_){var w=_.nodeName.toLowerCase(),M=window.getComputedStyle(_,null);if(x.canFocusScrollBody&&h.isScrollableContainer(_,u,w,M))return!0;if(x.canFocusChildrenOfFocusableFlexbox&&h.hasCssDisplayFlex(M))return!0}return!1}Object.defineProperty(n,"__esModule",{value:!0});var u=e("../prototype/element.prototype.matches"),a=o(u),i=e("../prototype/svgelement.prototype.focus"),l=o(i),s=e("../get/parents"),d=o(s),c=e("../util/context-to-element"),f=o(c),m=e("../util/get-window"),p=o(m),b=e("./valid-tabindex"),v=o(b),h=e("./is.util"),g=e("./focus-relevant.supports"),y=o(g),x=void 0;r.except=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=function(t){return r({context:t,except:e})};return t.rules=r,t};var _=r.except({});n["default"]=_,t.exports=n["default"]},{"../get/parents":17,"../prototype/element.prototype.matches":48,"../prototype/svgelement.prototype.focus":49,"../util/context-to-element":112,"../util/get-window":118,"./focus-relevant.supports":25,"./is.util":27,"./valid-tabindex":35}],25:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/focus-audio-without-controls"),i=o(a),l=e("../supports/focus-children-of-focusable-flexbox"),s=o(l),d=e("../supports/focus-fieldset"),c=o(d),f=e("../supports/focus-flexbox-container"),m=o(f),p=e("../supports/focus-img-ismap"),b=o(p),v=e("../supports/focus-img-usemap-tabindex"),h=o(v),g=e("../supports/focus-in-hidden-iframe"),y=o(g),x=e("../supports/focus-in-zero-dimension-object"),_=o(x),w=e("../supports/focus-label-tabindex"),M=o(w),E=e("../supports/focus-object-svg"),O=o(E),S=e("../supports/focus-object-svg-hidden"),P=o(S),A=e("../supports/focus-object-swf"),T=o(A),j=e("../supports/focus-redirect-img-usemap"),C=o(j),I=e("../supports/focus-redirect-legend"),k=o(I),F=e("../supports/focus-scroll-body"),L=o(F),N=e("../supports/focus-scroll-container"),D=o(N),q=e("../supports/focus-scroll-container-without-overflow"),R=o(q),B=e("../supports/focus-summary"),z=o(B),W=e("../supports/focus-svg"),H=o(W),G=e("../supports/focus-svg-focusable-attribute"),V=o(G),K=e("../supports/focus-table"),Z=o(K),U=e("../supports/focus-video-without-controls"),$=o(U),X=e("../supports/svg-focus-method"),J=o(X);n["default"]=u["default"](function(){return{canFocusAudioWithoutControls:i["default"](),canFocusChildrenOfFocusableFlexbox:s["default"](),canFocusFieldset:c["default"](),canFocusFlexboxContainer:m["default"](),canFocusImgIsmap:b["default"](),canFocusImgUsemapTabindex:h["default"](),canFocusInHiddenIframe:y["default"](),canFocusInZeroDimensionObject:_["default"](),canFocusLabelTabindex:M["default"](),canFocusObjectSvg:O["default"](),canFocusObjectSvgHidden:P["default"](),canFocusObjectSwf:T["default"](),canFocusRedirectImgUsemap:C["default"](),canFocusRedirectLegend:k["default"](),canFocusScrollBody:L["default"](),canFocusScrollContainer:D["default"](),canFocusScrollContainerWithoutOverflow:R["default"](),canFocusSummary:z["default"](),canFocusSvg:H["default"](),canFocusSvgFocusableAttribute:V["default"](),canFocusTable:Z["default"](),canFocusVideoWithoutControls:$["default"](),svgFocusMethod:J["default"]()}}),t.exports=n["default"]},{"../supports/focus-audio-without-controls":75,"../supports/focus-children-of-focusable-flexbox":77,"../supports/focus-fieldset":79,"../supports/focus-flexbox-container":80,"../supports/focus-img-ismap":82,"../supports/focus-img-usemap-tabindex":83,"../supports/focus-in-hidden-iframe":84,"../supports/focus-in-zero-dimension-object":85,"../supports/focus-label-tabindex":87,"../supports/focus-object-svg":89,"../supports/focus-object-svg-hidden":88,"../supports/focus-object-swf":90,"../supports/focus-redirect-img-usemap":91,"../supports/focus-redirect-legend":92,"../supports/focus-scroll-body":93,"../supports/focus-scroll-container":95,"../supports/focus-scroll-container-without-overflow":94,"../supports/focus-summary":96,"../supports/focus-svg":98,"../supports/focus-svg-focusable-attribute":97,"../supports/focus-table":100,"../supports/focus-video-without-controls":101,"../supports/memorize-result":107,"../supports/svg-focus-method":109}],26:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.nodeName.toLowerCase();if("embed"===t||"keygen"===t)return!0;var n=O["default"](e);if(e.shadowRoot&&null===n)return!0;if("label"===t)return!A.canFocusLabelTabindex||null===n;if("legend"===t)return null===n;var o=M["default"](e);if(i["default"](o),A.canFocusSvgFocusableAttribute&&(e.ownerSVGElement||"svg"===t)){var r=e.getAttribute("focusable");return r&&"false"===r}return"img"===t&&e.hasAttribute("usemap")?null===n||!A.canFocusImgUsemapTabindex:"area"===t?!c["default"](e):!1}function u(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.except,o=void 0===n?{disabled:!1,visible:!1,onlyTabbable:!1}:n;A||(A=P["default"]());var u=h["default"].rules.except({onlyFocusableBrowsingContext:!0,visible:o.visible}),a=y["default"]({label:"is/focusable",resolveDocument:!0,context:t}),i=s["default"].rules({context:a,except:o});if(!i||r(a))return!1;if(!o.disabled&&b["default"](a))return!1;if(!o.onlyTabbable&&u(a))return!1;if(!o.visible){var l={context:a,except:{}};if(A.canFocusInHiddenIframe&&(l.except.browsingContext=!0),A.canFocusObjectSvgHidden){var d=a.nodeName.toLowerCase();"object"===d&&(l.except.cssVisibility=!0)}if(!m["default"].rules(l))return!1}var c=_["default"](a);if(c){var f=c.nodeName.toLowerCase();if(!("object"!==f||A.canFocusInZeroDimensionObject||c.offsetWidth&&c.offsetHeight))return!1}return!0}Object.defineProperty(n,"__esModule",{value:!0});var a=e("../prototype/svgelement.prototype.focus"),i=o(a),l=e("./focus-relevant"),s=o(l),d=e("./valid-area"),c=o(d),f=e("./visible"),m=o(f),p=e("./disabled"),b=o(p),v=e("./only-tabbable"),h=o(v),g=e("../util/context-to-element"),y=o(g),x=e("../util/get-frame-element"),_=o(x),w=e("../util/get-window"),M=o(w),E=e("../util/tabindex-value"),O=o(E),S=e("./focus-relevant.supports"),P=o(S),A=void 0;u.except=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=function(t){return u({context:t,except:e})};return t.rules=u,t};var T=u.except({});n["default"]=T,t.exports=n["default"]},{"../prototype/svgelement.prototype.focus":49,"../util/context-to-element":112,"../util/get-frame-element":117,"../util/get-window":118,"../util/tabindex-value":126,"./disabled":22,"./focus-relevant":24,"./focus-relevant.supports":25,"./only-tabbable":30,"./valid-area":33,"./visible":37}],27:[function(e,t,n){"use strict";function o(e){var t=e.webkitUserModify||"";return Boolean(t&&-1!==t.indexOf("write"))}function r(e){return[e.getPropertyValue("overflow"),e.getPropertyValue("overflow-x"),e.getPropertyValue("overflow-y")].some(function(e){return"auto"===e||"scroll"===e})}function u(e){return e.display.indexOf("flex")>-1}function a(e,t,n,o){return"div"!==t&&"span"!==t?!1:n&&"div"!==n&&"span"!==n&&!r(o)?!1:e.offsetHeight<e.scrollHeight||e.offsetWidth<e.scrollWidth}Object.defineProperty(n,"__esModule",{value:!0}),n.isUserModifyWritable=o,n.hasCssOverflowScroll=r,n.hasCssDisplayFlex=u,n.isScrollableContainer=a},{}],28:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r),a=e("./native-disabled-supported.supports"),i=o(a),l=void 0,s=void 0,d={input:!0,select:!0,textarea:!0,button:!0,fieldset:!0,form:!0};n["default"]=function(e){l||(l=i["default"](),l.canFocusDisabledFieldset&&delete d.fieldset,l.canFocusDisabledForm&&delete d.form,s=new RegExp("^("+Object.keys(d).join("|")+")$"));var t=u["default"]({label:"is/native-disabled-supported",context:e}),n=t.nodeName.toLowerCase();return Boolean(s.test(n))},t.exports=n["default"]},{"../util/context-to-element":112,"./native-disabled-supported.supports":29}],29:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/focus-fieldset-disabled"),i=o(a),l=e("../supports/focus-form-disabled"),s=o(l);n["default"]=u["default"](function(){return{canFocusDisabledFieldset:i["default"](),canFocusDisabledForm:s["default"]()}}),t.exports=n["default"]},{"../supports/focus-fieldset-disabled":78,"../supports/focus-form-disabled":81,"../supports/memorize-result":107}],30:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.except,o=void 0===n?{onlyFocusableBrowsingContext:!1,visible:!1}:n,r=l["default"]({label:"is/only-tabbable",resolveDocument:!0,context:t});if(!o.visible&&!a["default"](r))return!1;if(!o.onlyFocusableBrowsingContext&&(v["default"].is.GECKO||v["default"].is.TRIDENT)){var u=d["default"](r);if(u&&p["default"](u)<0)return!1}var i=r.nodeName.toLowerCase(),s=p["default"](r);if("label"===i&&v["default"].is.GECKO)return null!==s&&s>=0;if("svg"===i&&v["default"].is.TRIDENT)return"false"!==r.getAttribute("focusable");var c=f["default"](r);if(r instanceof c.SVGElement){if("a"===i&&r.hasAttribute("xlink:href")){if(v["default"].is.GECKO)return!0;if(v["default"].is.TRIDENT)return"false"!==r.getAttribute("focusable")}if(v["default"].is.TRIDENT)return"true"===r.getAttribute("focusable");
}return!1}Object.defineProperty(n,"__esModule",{value:!0});var u=e("./visible"),a=o(u),i=e("../util/context-to-element"),l=o(i),s=e("../util/get-frame-element"),d=o(s),c=e("../util/get-window"),f=o(c),m=e("../util/tabindex-value"),p=o(m),b=e("../util/platform"),v=o(b);r.except=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=function(t){return r({context:t,except:e})};return t.rules=r,t};var h=r.except({});n["default"]=h,t.exports=n["default"]},{"../util/context-to-element":112,"../util/get-frame-element":117,"../util/get-window":118,"../util/platform":123,"../util/tabindex-value":126,"./visible":37}],31:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r),a=e("../get/shadow-host"),i=o(a);n["default"]=function(e){var t=u["default"]({label:"is/shadowed",resolveDocument:!0,context:e});return Boolean(i["default"]({context:t}))},t.exports=n["default"]},{"../get/shadow-host":19,"../util/context-to-element":112}],32:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.except,o=void 0===n?{flexbox:!1,scrollable:!1,shadow:!1,visible:!1,onlyTabbable:!1}:n,r=l["default"]({label:"is/tabbable",resolveDocument:!0,context:t});if(v["default"].is.BLINK&&v["default"].is.ANDROID&&v["default"].majorVersion>42)return!1;var u=p["default"](r);if(u){if(v["default"].is.WEBKIT&&v["default"].is.IOS&&v["default"].majorVersion<10)return!1;if(d["default"](u)<0)return!1;if(!o.visible&&(v["default"].is.BLINK||v["default"].is.WEBKIT)&&!a["default"](u))return!1;var i=u.nodeName.toLowerCase();if("object"===i&&(v["default"].is.BLINK||v["default"].is.WEBKIT))return!1}var s=r.nodeName.toLowerCase(),c=d["default"](r),f=null===c?null:c>=0,m=f!==!1,b=null!==c&&c>=0;if(r.hasAttribute("contenteditable"))return m;if(y.test(s)&&f!==!0)return!1;if(void 0===r.tabIndex)return Boolean(o.onlyTabbable);if("audio"===s){if(!r.hasAttribute("controls"))return!1;if(v["default"].is.BLINK)return!0}if("video"===s)if(r.hasAttribute("controls")){if(v["default"].is.BLINK||v["default"].is.GECKO)return!0}else if(v["default"].is.TRIDENT)return!1;if("object"===s&&(v["default"].is.BLINK||v["default"].is.WEBKIT))return!1;if("iframe"===s)return!1;if(v["default"].is.WEBKIT&&v["default"].is.IOS){var w="input"===s&&"text"===r.type||"password"===r.type||"select"===s||"textarea"===s||r.hasAttribute("contenteditable");if(!w){var M=window.getComputedStyle(r,null);w=g.isUserModifyWritable(M)}if(!w)return!1}if(v["default"].is.GECKO){var M=window.getComputedStyle(r,null);if(g.hasCssOverflowScroll(M))return m}if(v["default"].is.TRIDENT){if("area"===s){var E=h.getImageOfArea(r);if(E&&d["default"](E)<0)return!1}var M=window.getComputedStyle(r,null);if(g.isUserModifyWritable(M))return r.tabIndex>=0;if(!o.flexbox&&g.hasCssDisplayFlex(M))return null!==c?b:x(r)&&_(r);if(g.isScrollableContainer(r,s))return!1;var O=r.parentElement;if(O){var S=O.nodeName.toLowerCase(),P=window.getComputedStyle(O,null);if(g.isScrollableContainer(O,s,S,P))return!1;if(g.hasCssDisplayFlex(P))return b}}return r.tabIndex>=0}Object.defineProperty(n,"__esModule",{value:!0});var u=e("./visible"),a=o(u),i=e("../util/context-to-element"),l=o(i),s=e("../util/tabindex-value"),d=o(s),c=e("./focus-relevant"),f=o(c),m=e("../util/get-frame-element"),p=o(m),b=e("../util/platform"),v=o(b),h=e("../util/image-map"),g=e("./is.util"),y=/^(fieldset|table|td|body)$/,x=void 0,_=void 0;r.except=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=function(t){return r({context:t,except:e})};return t.rules=r,t},x=f["default"].rules.except({flexbox:!0}),_=r.except({flexbox:!0});var w=r.except({});n["default"]=w,t.exports=n["default"]},{"../util/context-to-element":112,"../util/get-frame-element":117,"../util/image-map":119,"../util/platform":123,"../util/tabindex-value":126,"./focus-relevant":24,"./is.util":27,"./visible":37}],33:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r),a=e("./visible"),i=o(a),l=e("../get/parents"),s=o(l),d=e("../util/image-map"),c=e("./valid-area.supports"),f=o(c),m=void 0;n["default"]=function(e){m||(m=f["default"]());var t=u["default"]({label:"is/valid-area",context:e}),n=t.nodeName.toLowerCase();if("area"!==n)return!1;var o=t.hasAttribute("tabindex");if(!m.canFocusAreaTabindex&&o)return!1;var r=d.getImageOfArea(t);if(!r||!i["default"](r))return!1;if(!m.canFocusBrokenImageMaps&&(!r.complete||!r.naturalHeight||r.offsetWidth<=0||r.offsetHeight<=0))return!1;if(!m.canFocusAreaWithoutHref&&!t.href)return m.canFocusAreaTabindex&&o||m.canFocusAreaImgTabindex&&r.hasAttribute("tabindex");var a=s["default"]({context:r}).slice(1).some(function(e){var t=e.nodeName.toLowerCase();return"button"===t||"a"===t});return a?!1:!0},t.exports=n["default"]},{"../get/parents":17,"../util/context-to-element":112,"../util/image-map":119,"./valid-area.supports":34,"./visible":37}],34:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/focus-area-img-tabindex"),i=o(a),l=e("../supports/focus-area-tabindex"),s=o(l),d=e("../supports/focus-area-without-href"),c=o(d),f=e("../supports/focus-broken-image-map"),m=o(f);n["default"]=u["default"](function(){return{canFocusAreaImgTabindex:i["default"](),canFocusAreaTabindex:s["default"](),canFocusAreaWithoutHref:c["default"](),canFocusBrokenImageMaps:m["default"]()}}),t.exports=n["default"]},{"../supports/focus-area-img-tabindex":72,"../supports/focus-area-tabindex":73,"../supports/focus-area-without-href":74,"../supports/focus-broken-image-map":76,"../supports/memorize-result":107}],35:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r),a=e("./valid-tabindex.supports"),i=o(a),l=void 0,s=/^\s*(-|\+)?[0-9]+\s*$/,d=/^\s*(-|\+)?[0-9]+.*$/;n["default"]=function(e){l||(l=i["default"]());var t=l.allowsTrailingCharacters?d:s,n=u["default"]({label:"is/valid-tabindex",resolveDocument:!0,context:e});if(!n.hasAttribute("tabindex"))return!1;if(void 0===n.tabIndex)return!1;if(l.allowsInvalidValue)return!0;var o=n.getAttribute("tabindex");return"-32768"===o?!1:Boolean(o&&t.test(o))},t.exports=n["default"]},{"../util/context-to-element":112,"./valid-tabindex.supports":36}],36:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/focus-invalid-tabindex"),i=o(a),l=e("../supports/focus-tabindex-trailing-characters"),s=o(l);n["default"]=u["default"](function(){return{allowsInvalidValue:i["default"](),allowsTrailingCharacters:s["default"]()}}),t.exports=n["default"]},{"../supports/focus-invalid-tabindex":86,"../supports/focus-tabindex-trailing-characters":99,"../supports/memorize-result":107}],37:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){return window.getComputedStyle(e,null).getPropertyValue(t)}function u(e){return e.some(function(e){return"none"===r(e,"display")})}function a(e){var t=e.findIndex(function(e){var t=r(e,"visibility");return"hidden"===t||"collapse"===t});if(-1===t)return!1;var n=e.findIndex(function(e){return"visible"===r(e,"visibility")});return-1===n?!0:n>t?!0:!1}function i(e){var t=1;return"summary"===e[0].nodeName.toLowerCase()&&(t=2),e.slice(t).some(function(e){return"details"===e.nodeName.toLowerCase()&&e.open===!1})}function l(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.except,o=void 0===n?{notRendered:!1,cssDisplay:!1,cssVisibility:!1,detailsElement:!1,browsingContext:!1}:n,r=f["default"]({label:"is/visible",resolveDocument:!0,context:t}),s=r.nodeName.toLowerCase();if(!o.notRendered&&b.test(s))return!0;var c=d["default"]({context:r}),m="audio"===s&&!r.hasAttribute("controls");if(!o.cssDisplay&&u(m?c.slice(1):c))return!1;if(!o.cssVisibility&&a(c))return!1;if(!o.detailsElement&&i(c))return!1;if(!o.browsingContext){var v=p["default"](r),h=l.except(o);if(v&&!h(v))return!1}return!0}Object.defineProperty(n,"__esModule",{value:!0}),e("array.prototype.findindex");var s=e("../get/parents"),d=o(s),c=e("../util/context-to-element"),f=o(c),m=e("../util/get-frame-element"),p=o(m),b=/^(area)$/;l.except=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=function(t){return l({context:t,except:e})};return t.rules=l,t};var v=l.except({});n["default"]=v,t.exports=n["default"]},{"../get/parents":17,"../util/context-to-element":112,"../util/get-frame-element":117,"array.prototype.findindex":135}],38:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./disabled"),u=o(r),a=e("./hidden"),i=o(a),l=e("./tab-focus"),s=o(l);n["default"]={disabled:u["default"],hidden:i["default"],tabFocus:s["default"]},t.exports=n["default"]},{"./disabled":39,"./hidden":40,"./tab-focus":41}],39:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e){return m["default"](e,!0)}function a(e){return m["default"](e,!1)}Object.defineProperty(n,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=e("../util/node-array"),s=o(l),d=e("../query/focusable"),c=o(d),f=e("../element/disabled"),m=o(f),p=e("../observe/shadow-mutations"),b=o(p),v=e("../util/compare-position"),h={attributes:!0,childList:!0,subtree:!0,attributeFilter:["tabindex","disabled","data-ally-disabled"]},g=function(){function e(){var t=this,n=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],o=n.context,u=n.filter;r(this,e),this._context=s["default"](o||document.documentElement)[0],this._filter=s["default"](u),this._inertElementCache=[],this.disengage=this.disengage.bind(this),this.handleMutation=this.handleMutation.bind(this),this.renderInert=this.renderInert.bind(this),this.filterElements=this.filterElements.bind(this),this.filterParentElements=this.filterParentElements.bind(this);var a=c["default"]({context:this._context,includeContext:!0,strategy:"all"});this.renderInert(a),this.shadowObserver=b["default"]({context:this._context,config:h,callback:function(e){return e.forEach(t.handleMutation)}})}return i(e,[{key:"disengage",value:function(){this._context&&(a(this._context),this._inertElementCache.forEach(function(e){return a(e)}),this._inertElementCache=null,this._filter=null,this._context=null,this.shadowObserver&&this.shadowObserver.disengage(),this.shadowObserver=null)}},{key:"listQueryFocusable",value:function(e){return e.map(function(e){return c["default"]({context:e,includeContext:!0,strategy:"all"})}).reduce(function(e,t){return e.concat(t)},[])}},{key:"renderInert",value:function(e){var t=this,n=function(e){t._inertElementCache.push(e),u(e)};e.filter(this.filterElements).filter(this.filterParentElements).filter(function(e){return!m["default"](e)}).forEach(n)}},{key:"filterElements",value:function(e){var t=v.getParentComparator({element:e,includeSelf:!0});return!this._filter.some(t)}},{key:"filterParentElements",value:function(e){var t=v.getParentComparator({parent:e});return!this._filter.some(t)}},{key:"handleMutation",value:function(e){if("childList"===e.type){var t=s["default"](e.addedNodes).filter(function(e){return e.nodeType===Node.ELEMENT_NODE});if(!t.length)return;var n=this.listQueryFocusable(t);this.renderInert(n)}else"attributes"===e.type&&this.renderInert([e.target])}}]),e}();n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.filter,o=new g({context:t,filter:n});return{disengage:o.disengage}},t.exports=n["default"]},{"../element/disabled":3,"../observe/shadow-mutations":47,"../query/focusable":54,"../util/compare-position":111,"../util/node-array":122}],40:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e){b["default"]({element:e,attribute:"aria-hidden",temporaryValue:"true"})}function a(e){b["default"]({element:e,attribute:"aria-hidden"})}Object.defineProperty(n,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=e("../util/node-array"),s=o(l),d=e("../get/insignificant-branches"),c=o(d),f=e("../get/parents"),m=o(f),p=e("../util/toggle-attribute-value"),b=o(p),v=e("../util/compare-position"),h={attributes:!1,childList:!0,subtree:!0},g=function(){function e(){var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=t.context,o=t.filter;r(this,e),this._context=s["default"](n||document.documentElement)[0],this._filter=s["default"](o),this.disengage=this.disengage.bind(this),this.handleMutation=this.handleMutation.bind(this),this.isInsignificantBranch=this.isInsignificantBranch.bind(this);var a=c["default"]({context:this._context,filter:this._filter});a.forEach(u),this.startObserver()}return i(e,[{key:"disengage",value:function(){this._context&&([].forEach.call(this._context.querySelectorAll("[data-cached-aria-hidden]"),a),this._context=null,this._filter=null,this._observer&&this._observer.disconnect(),this._observer=null)}},{key:"startObserver",value:function(){var e=this;window.MutationObserver&&(this._observer=new MutationObserver(function(t){return t.forEach(e.handleMutation)}),this._observer.observe(this._context,h))}},{key:"handleMutation",value:function(e){"childList"===e.type&&s["default"](e.addedNodes).filter(function(e){return e.nodeType===Node.ELEMENT_NODE}).filter(this.isInsignificantBranch).forEach(u)}},{key:"isInsignificantBranch",value:function(e){var t=m["default"]({context:e});if(t.some(function(e){return"true"===e.getAttribute("aria-hidden")}))return!1;var n=v.getParentComparator({element:e});return this._filter.some(n)?!1:!0}}]),e}();n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.filter,o=new g({context:t,filter:n});return{disengage:o.disengage}},t.exports=n["default"]},{"../get/insignificant-branches":16,"../get/parents":17,"../util/compare-position":111,"../util/node-array":122,"../util/toggle-attribute-value":127}],41:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../is/active-element"),u=o(r),a=e("../query/tabsequence"),i=o(a),l=e("../when/key"),s=o(l);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context;return t||(t=document.documentElement),i["default"](),s["default"]({"?shift+tab":function(e){e.preventDefault();var n=i["default"]({context:t}),o=e.shiftKey,r=n[0],a=n[n.length-1],l=o?r:a,s=o?a:r;if(u["default"](l))return void s.focus();var d=void 0,c=n.some(function(e,t){return u["default"](e)?(d=t,!0):!1});if(!c)return void r.focus();var f=o?-1:1;n[d+f].focus()}})},t.exports=n["default"]},{"../is/active-element":21,"../query/tabsequence":59,"../when/key":133}],42:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./attribute"),u=o(r),a=e("./keycode"),i=o(a);n["default"]={attribute:u["default"],keycode:i["default"]},t.exports=n["default"]},{"./attribute":43,"./keycode":44}],43:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={"aria-busy":{"default":"false",values:["true","false"]},"aria-checked":{"default":void 0,values:["true","false","mixed",void 0]},"aria-disabled":{"default":"false",values:["true","false"]},"aria-expanded":{"default":void 0,values:["true","false",void 0]},"aria-grabbed":{"default":void 0,values:["true","false",void 0]},"aria-hidden":{"default":"false",values:["true","false"]},"aria-invalid":{"default":"false",values:["true","false","grammar","spelling"]},"aria-pressed":{"default":void 0,values:["true","false","mixed",void 0]},"aria-selected":{"default":void 0,values:["true","false",void 0]},"aria-atomic":{"default":"false",values:["true","false"]},"aria-autocomplete":{"default":"none",values:["inline","list","both","none"]},"aria-dropeffect":{"default":"none",multiple:!0,values:["copy","move","link","execute","popup","none"]},"aria-haspopup":{"default":"false",values:["true","false"]},"aria-live":{"default":"off",values:["off","polite","assertive"]},"aria-multiline":{"default":"false",values:["true","false"]},"aria-multiselectable":{"default":"false",values:["true","false"]},"aria-orientation":{"default":"horizontal",values:["vertical","horizontal"]},"aria-readonly":{"default":"false",values:["true","false"]},"aria-relevant":{"default":"additions text",multiple:!0,values:["additions","removals","text","all"]},"aria-required":{"default":"false",values:["true","false"]},"aria-sort":{"default":"none",other:!0,values:["ascending","descending","none"]}},t.exports=n["default"]},{}],44:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});for(var o={tab:9,left:37,up:38,right:39,down:40,pageUp:33,"page-up":33,pageDown:34,"page-down":34,end:35,home:36,enter:13,escape:27,space:32,shift:16,capsLock:20,"caps-lock":20,ctrl:17,alt:18,meta:91,pause:19,insert:45,"delete":46,backspace:8,_alias:{91:[92,93,224]}},r=1;26>r;r++)o["f"+r]=r+111;for(var r=0;10>r;r++){var u=r+48,a=r+96;o[r]=u,o["num-"+r]=a,o._alias[u]=[a]}for(var r=0;26>r;r++){var u=r+65,i=String.fromCharCode(u).toLowerCase();o[i]=u}n["default"]=o,t.exports=n["default"]},{}],45:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./interaction-type"),u=o(r),a=e("./shadow-mutations"),i=o(a);n["default"]={interactionType:u["default"],shadowMutations:i["default"]},t.exports=n["default"]},{"./interaction-type":46,"./shadow-mutations":47}],46:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){p=0,b=0}function u(e){e.isPrimary!==!1&&p++}function a(e){return e.isPrimary!==!1?e.touches?void(p=e.touches.length):void(window.setImmediate||window.setTimeout)(function(){p=Math.max(p-1,0)}):void 0}function i(e){switch(e.keyCode||e.which){case 16:case 17:case 18:case 91:case 93:return}b++}function l(e){switch(e.keyCode||e.which){case 16:case 17:case 18:case 91:case 93:return}(window.setImmediate||window.setTimeout)(function(){b=Math.max(b-1,0)})}function s(){return{pointer:Boolean(p),key:Boolean(b)}}function d(){p=b=0,window.removeEventListener("blur",r,!1),document.documentElement.removeEventListener("keydown",i,!0),document.documentElement.removeEventListener("keyup",l,!0),v.forEach(function(e){document.documentElement.removeEventListener(e,u,!0)}),h.forEach(function(e){document.documentElement.removeEventListener(e,a,!0)})}function c(){return window.addEventListener("blur",r,!1),document.documentElement.addEventListener("keydown",i,!0),document.documentElement.addEventListener("keyup",l,!0),v.forEach(function(e){document.documentElement.addEventListener(e,u,!0)}),h.forEach(function(e){document.documentElement.addEventListener(e,a,!0)}),{get:s}}Object.defineProperty(n,"__esModule",{value:!0});var f=e("../util/decorate-service"),m=o(f),p=0,b=0,v=["touchstart","pointerdown","MSPointerDown","mousedown"],h=["touchend","touchcancel","pointerup","MSPointerUp","pointercancel","MSPointerCancel","mouseup"];n["default"]=m["default"]({engage:c,disengage:d}),t.exports=n["default"]},{"../util/decorate-service":114}],47:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=e("../util/node-array"),i=o(a),l=e("../query/shadow-hosts"),s=o(l),d=e("../util/context-to-element"),c=o(d),f={childList:!0,subtree:!0},m=function(){function e(){var t=this,n=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],o=n.context,u=n.callback,a=n.config;r(this,e),this.config=a,this.disengage=this.disengage.bind(this),this.clientObserver=new MutationObserver(u),this.hostObserver=new MutationObserver(function(e){return e.forEach(t.handleHostMutation,t)}),this.observeContext(o),this.observeShadowHosts(o)}return u(e,[{key:"disengage",value:function(){this.clientObserver&&this.clientObserver.disconnect(),this.clientObserver=null,this.hostObserver&&this.hostObserver.disconnect(),this.hostObserver=null}},{key:"observeShadowHosts",value:function(e){var t=this,n=s["default"]({context:e});n.forEach(function(e){return t.observeContext(e.shadowRoot)})}},{key:"observeContext",value:function(e){this.clientObserver.observe(e,this.config),this.hostObserver.observe(e,f)}},{key:"handleHostMutation",value:function(e){if("childList"===e.type){var t=i["default"](e.addedNodes).filter(function(e){return e.nodeType===Node.ELEMENT_NODE});t.forEach(this.observeShadowHosts,this)}}}]),e}();n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.callback,o=e.config;if("function"!=typeof n)throw new TypeError("observe/shadow-mutations requires options.callback to be a function");if("object"!=typeof o)throw new TypeError("observe/shadow-mutations requires options.config to be an object");if(!window.MutationObserver)return{disengage:function(){}};var r=c["default"]({label:"observe/shadow-mutations",resolveDocument:!0,defaultToDocument:!0,context:t}),u=new m({context:r,callback:n,config:o});return{disengage:u.disengage}},t.exports=n["default"]},{"../query/shadow-hosts":57,"../util/context-to-element":112,"../util/node-array":122}],48:[function(e,t,n){"use strict";function o(e){e.Element.prototype.matches||"webkitMatchesSelector mozMatchesSelector msMatchesSelector".split(" ").some(function(t){return e.Element.prototype[t]?(e.Element.prototype.matches=e.Element.prototype[t],!0):!1})}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=o,"undefined"!=typeof window&&o(window),t.exports=n["default"]},{}],49:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){if(e.SVGElement&&!e.SVGElement.prototype.focus){var t=void 0;try{t=e.document.activeElement}catch(n){t=null}try{var o=e.document.createElement("div");o.innerHTML='<svg xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><rect x="0" y="0" width="1" height="1"></svg>';var r=o.firstElementChild.firstElementChild;e.document.body.focus.call(r),e.SVGElement.prototype.focus=e.HTMLElement.prototype.focus,e.SVGElement.prototype.blur=e.HTMLElement.prototype.blur,e.SVGElement.prototype.focus._polyfill="reassigned",e.SVGElement.prototype.blur._polyfill="reassigned"}catch(n){e.SVGElement.prototype.focus=function(){a["default"].warn("SVGElement.focus() not possible")},e.SVGElement.prototype.blur=function(){a["default"].warn("SVGElement.blur() not possible")},e.SVGElement.prototype.focus._polyfill="noop",e.SVGElement.prototype.blur._polyfill="noop"}null!==t&&(e.document.activeElement&&e.document.activeElement.blur(),t.focus())}}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=r;var u=e("../util/logger"),a=o(u);"undefined"!=typeof window&&r(window),t.exports=n["default"]},{"../util/logger":120}],50:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o="undefined"!=typeof window&&window.CustomEvent||function(){};"function"!=typeof o&&(o=function(e,t){var n=document.createEvent("CustomEvent");return!t&&(t={bubbles:!1,cancelable:!1,detail:void 0}),n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n},o.prototype=window.Event.prototype),n["default"]=o,t.exports=n["default"]},{}],51:[function(){"use strict";"undefined"!=typeof window&&function(){for(var e=0,t=["ms","moz","webkit","o"],n="",o="",r=0,u=t.length;u>r;++r)n=window[t[r]+"RequestAnimationFrame"],o=window[t[r]+"CancelAnimationFrame"]||window[t[r]+"CancelRequestAnimationFrame"];"function"!=typeof window.requestAnimationFrame&&(window.requestAnimationFrame=window[n]||function(t){var n=(new Date).getTime(),o=Math.max(0,16-(n-e)),r=window.setTimeout(function(){t(n+o)},o);return e=n+o,r}),"function"!=typeof window.cancelAnimationFrame&&(window.cancelAnimationFrame=window[o]||function(e){clearTimeout(e)})}()},{}],52:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./first-tabbable"),u=o(r),a=e("./focusable"),i=o(a),l=e("./shadow-hosts"),s=o(l),d=e("./tabbable"),c=o(d),f=e("./tabsequence"),m=o(f);n["default"]={firstTabbable:u["default"],focusable:i["default"],shadowHosts:s["default"],tabbable:c["default"],tabsequence:m["default"]},t.exports=n["default"]},{"./first-tabbable":53,"./focusable":54,"./shadow-hosts":57,"./tabbable":58,"./tabsequence":59}],53:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){return e.hasAttribute("autofocus")}function u(e){return e.tabIndex<=0}Object.defineProperty(n,"__esModule",{value:!0}),e("array.prototype.findindex");var a=e("./tabbable"),i=o(a),l=e("../is/focusable"),s=o(l),d=e("../util/node-array"),c=o(d);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.sequence,o=e.strategy,a=e.ignoreAutofocus,l=e.defaultToContext,d=e.includeOnlyTabbable,f=-1;n||(t=c["default"](t||document.body)[0],n=i["default"]({context:t,includeOnlyTabbable:d,strategy:o})),n.length&&!a&&(f=n.findIndex(r)),n.length&&-1===f&&(f=n.findIndex(u));var m=s["default"].rules.except({onlyTabbable:d});return-1===f&&l&&t&&m(t)?t:n[f]||null},t.exports=n["default"]},{"../is/focusable":26,"../util/node-array":122,"./tabbable":58,"array.prototype.findindex":135}],54:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/context-to-element"),u=o(r),a=e("./focusable.strict"),i=o(a),l=e("./focusable.quick"),s=o(l);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.includeContext,o=e.includeOnlyTabbable,r=e.strategy,a=void 0===r?"quick":r,l=u["default"]({label:"query/focusable",resolveDocument:!0,defaultToDocument:!0,context:t}),d={context:l,includeContext:n,includeOnlyTabbable:o,strategy:a};if("quick"===a)return s["default"](d);if("strict"===a||"all"===a)return i["default"](d);throw new TypeError('query/focusable requires option.strategy to be one of ["quick", "strict", "all"]')},t.exports=n["default"]},{"../util/context-to-element":112,"./focusable.quick":55,"./focusable.strict":56}],55:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.includeContext,o=e.includeOnlyTabbable,r=a["default"](),u=t.querySelectorAll(r),i=l["default"].rules.except({onlyTabbable:o}),s=[].filter.call(u,i);return n&&i(t)&&s.unshift(t),s}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=r;var u=e("../selector/focusable"),a=o(u),i=e("../is/focusable"),l=o(i);t.exports=n["default"]},{"../is/focusable":26,"../selector/focusable":64}],56:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=function(t){return t.shadowRoot?NodeFilter.FILTER_ACCEPT:e(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP};return t.acceptNode=t,t}function u(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.includeContext,o=e.includeOnlyTabbable,a=e.strategy;t||(t=document.documentElement);for(var l=i["default"].rules.except({onlyTabbable:o}),d=c["default"](t),m=d.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,"all"===a?f:r(l),!1),p=[];m.nextNode();)m.currentNode.shadowRoot?(l(m.currentNode)&&p.push(m.currentNode),p=p.concat(u({context:m.currentNode.shadowRoot,includeOnlyTabbable:o,strategy:a}))):p.push(m.currentNode);return n&&("all"===a?s["default"](t)&&p.unshift(t):l(t)&&p.unshift(t)),p}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=u;var a=e("../is/focusable"),i=o(a),l=e("../is/focus-relevant"),s=o(l),d=e("../util/get-document"),c=o(d),f=r(s["default"]);t.exports=n["default"]},{"../is/focus-relevant":24,"../is/focusable":26,"../util/get-document":116}],57:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=a["default"]({label:"query/shadow-hosts",resolveDocument:!0,defaultToDocument:!0,context:t}),o=l["default"](t),u=o.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,s,!1),i=[];for(n.shadowRoot&&(i.push(n),i=i.concat(r({context:n.shadowRoot})));u.nextNode();)i.push(u.currentNode),i=i.concat(r({context:u.currentNode.shadowRoot}));return i}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=r;var u=e("../util/context-to-element"),a=o(u),i=e("../util/get-document"),l=o(i),s=function(e){return e.shadowRoot?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP};s.acceptNode=s,t.exports=n["default"]},{"../util/context-to-element":112,"../util/get-document":116}],58:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./focusable"),u=o(r),a=e("../is/tabbable"),i=o(a);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.includeContext,o=e.includeOnlyTabbable,r=e.strategy,a=i["default"].rules.except({onlyTabbable:o});return u["default"]({context:t,includeContext:n,includeOnlyTabbable:o,strategy:r}).filter(a)},t.exports=n["default"]},{"../is/tabbable":32,"./focusable":54}],59:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n=e.indexOf(t);if(n>0){var o=e.splice(n,1);return o.concat(e)}return e}function u(e,t){return x.tabsequenceSortsAreaAtImagePosition&&(e=m["default"](e,t)),e=h["default"](e)}Object.defineProperty(n,"__esModule",{value:!0});var a=e("./tabbable"),i=o(a),l=e("../util/node-array"),s=o(l),d=e("../util/platform"),c=o(d),f=e("./tabsequence.sort-area"),m=o(f),p=e("./tabsequence.sort-shadowed"),b=o(p),v=e("./tabsequence.sort-tabindex"),h=o(v),g=e("./tabsequence.supports"),y=o(g),x=void 0;n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.includeContext,o=e.includeOnlyTabbable,a=e.strategy;x||(x=y["default"]());var l=s["default"](t)[0]||document.documentElement,d=i["default"]({context:l,includeContext:n,includeOnlyTabbable:o,strategy:a});return d=document.body.createShadowRoot&&c["default"].is.BLINK?b["default"](d,l,u):u(d,l),n&&(d=r(d,l)),d},t.exports=n["default"]},{"../util/node-array":122,"../util/platform":123,"./tabbable":58,"./tabsequence.sort-area":60,"./tabsequence.sort-shadowed":61,"./tabsequence.sort-tabindex":62,"./tabsequence.supports":63}],60:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{
"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=e("./tabbable"),i=o(a),l=e("../util/merge-dom-order"),s=o(l),d=e("../util/get-document"),c=o(d),f=e("../util/image-map"),m=function(){function e(t){r(this,e),this._document=c["default"](t),this.maps={}}return u(e,[{key:"getAreasFor",value:function(e){return this.maps[e]||this.addMapByName(e),this.maps[e]}},{key:"addMapByName",value:function(e){var t=f.getMapByName(e,this._document);t&&(this.maps[t.name]=i["default"]({context:t}))}},{key:"extractAreasFromList",value:function(e){return e.filter(function(e){var t=e.nodeName.toLowerCase();if("area"!==t)return!0;var n=e.parentNode;return this.maps[n.name]||(this.maps[n.name]=[]),this.maps[n.name].push(e),!1},this)}}]),e}();n["default"]=function(e,t){var n=t.querySelectorAll("img[usemap]"),o=new m(t),r=o.extractAreasFromList(e);return n.length?s["default"]({list:r,elements:n,resolveElement:function(e){var t=e.getAttribute("usemap").slice(1);return o.getAreasFor(t)}}):r},t.exports=n["default"]},{"../util/get-document":116,"../util/image-map":119,"../util/merge-dom-order":121,"./tabbable":58}],61:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=e("../get/shadow-host"),i=o(a),l=e("../util/merge-dom-order"),s=o(l),d=e("../util/tabindex-value"),c=o(d),f=function(){function e(t,n){r(this,e),this.context=t,this.sortElements=n,this.hostCounter=1,this.inHost={},this.inDocument=[],this.hosts={},this.elements={}}return u(e,[{key:"_registerHost",value:function(e){if(!e._sortingId){e._sortingId="shadow-"+this.hostCounter++,this.hosts[e._sortingId]=e;var t=i["default"]({context:e});t?(this._registerHost(t),this._registerHostParent(e,t)):this.inDocument.push(e)}}},{key:"_registerHostParent",value:function(e,t){this.inHost[t._sortingId]||(this.inHost[t._sortingId]=[]),this.inHost[t._sortingId].push(e)}},{key:"_registerElement",value:function(e,t){this.elements[t._sortingId]||(this.elements[t._sortingId]=[]),this.elements[t._sortingId].push(e)}},{key:"extractElements",value:function(e){return e.filter(function(e){var t=i["default"]({context:e});return t?(this._registerHost(t),this._registerElement(e,t),!1):!0},this)}},{key:"sort",value:function(e){var t=this._injectHosts(e);return t=this._replaceHosts(t),this._cleanup(),t}},{key:"_injectHosts",value:function(e){return Object.keys(this.hosts).forEach(function(e){var t=this.elements[e],n=this.inHost[e],o=this.hosts[e].shadowRoot;this.elements[e]=this._merge(t,n,o)},this),this._merge(e,this.inDocument,this.context)}},{key:"_merge",value:function(e,t,n){var o=s["default"]({list:e,elements:t});return this.sortElements(o,n)}},{key:"_replaceHosts",value:function(e){return s["default"]({list:e,elements:this.inDocument,resolveElement:this._resolveHostElement.bind(this)})}},{key:"_resolveHostElement",value:function(e){var t=s["default"]({list:this.elements[e._sortingId],elements:this.inHost[e._sortingId],resolveElement:this._resolveHostElement.bind(this)}),n=c["default"](e);return null!==n&&n>-1?[e].concat(t):t}},{key:"_cleanup",value:function(){Object.keys(this.hosts).forEach(function(e){delete this.hosts[e]._sortingId},this)}}]),e}();n["default"]=function(e,t,n){var o=new f(t,n),r=o.extractElements(e);return r.length===e.length?n(e):o.sort(r)},t.exports=n["default"]},{"../get/shadow-host":19,"../util/merge-dom-order":121,"../util/tabindex-value":126}],62:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){var t={},n=[],o=e.filter(function(e){return e.tabIndex<=0||void 0===e.tabIndex?!0:(t[e.tabIndex]||(t[e.tabIndex]=[],n.push(e.tabIndex)),t[e.tabIndex].push(e),!1)}),r=n.sort().map(function(e){return t[e]}).reduceRight(function(e,t){return t.concat(e)},o);return r},t.exports=n["default"]},{}],63:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/tabsequence-area-at-img-position"),i=o(a);n["default"]=u["default"](function(){return{tabsequenceSortsAreaAtImagePosition:i["default"]()}}),t.exports=n["default"]},{"../supports/memorize-result":107,"../supports/tabsequence-area-at-img-position":110}],64:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0}),e("../prototype/svgelement.prototype.focus");var r=e("../util/select-in-shadows"),u=o(r),a=e("./focusable.supports"),i=o(a),l=void 0,s=void 0;n["default"]=function(){return l||(l=i["default"]()),"string"==typeof s?s:(s=""+(l.canFocusTable?"table, td,":"")+(l.canFocusFieldset?"fieldset,":"")+"svg a,a[href],area[href],input, select, textarea, button,iframe, object, embed,keygen,"+(l.canFocusAudioWithoutControls?"audio,":"audio[controls],")+(l.canFocusVideoWithoutControls?"video,":"video[controls],")+(l.canFocusSummary?"summary,":"")+"[tabindex],[contenteditable]",s=u["default"](s))},t.exports=n["default"]},{"../prototype/svgelement.prototype.focus":49,"../util/select-in-shadows":124,"./focusable.supports":65}],65:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/focus-audio-without-controls"),i=o(a),l=e("../supports/focus-video-without-controls"),s=o(l),d=e("../supports/focus-table"),c=o(d),f=e("../supports/focus-fieldset"),m=o(f),p=e("../supports/focus-summary"),b=o(p);n["default"]=u["default"](function(){return{canFocusAudioWithoutControls:i["default"](),canFocusVideoWithoutControls:s["default"](),canFocusTable:c["default"](),canFocusFieldset:m["default"](),canFocusSummary:b["default"]()}}),t.exports=n["default"]},{"../supports/focus-audio-without-controls":75,"../supports/focus-fieldset":79,"../supports/focus-summary":96,"../supports/focus-table":100,"../supports/focus-video-without-controls":101,"../supports/memorize-result":107}],66:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./focus-source"),u=o(r),a=e("./focus-within"),i=o(a);n["default"]={focusSource:u["default"],focusWithin:i["default"]},t.exports=n["default"]},{"./focus-source":67,"./focus-within":68}],67:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t="";if(e.type===v||"shadow-focus"===e.type){var n=g.get();t=_||n.pointer&&"pointer"||n.key&&"key"||"script"}else"initial"===e.type&&(t="initial");document.documentElement.setAttribute("data-focus-source",t),e.type!==h&&(w[t]||document.documentElement.classList.add("focus-source-"+t),w[t]=!0,x=t)}function u(){return x}function a(e){return w[e]}function i(e){_=e}function l(){r({type:h}),x=_=null,Object.keys(w).forEach(function(e){document.documentElement.classList.remove("focus-source-"+e),w[e]=!1}),g.disengage(),y&&y.disengage(),document.removeEventListener("shadow-focus",r,!0),document.documentElement.removeEventListener(v,r,!0),document.documentElement.removeEventListener(h,r,!0),document.documentElement.removeAttribute("data-focus-source")}function s(){return y=c["default"](),document.addEventListener("shadow-focus",r,!0),document.documentElement.addEventListener(v,r,!0),document.documentElement.addEventListener(h,r,!0),g=m["default"](),r({type:"initial"}),{used:a,current:u,lock:i}}Object.defineProperty(n,"__esModule",{value:!0}),e("domtokenlist-shim/dist/domtokenlist-polyfill-umd");var d=e("../event/shadow-focus"),c=o(d),f=e("../observe/interaction-type"),m=o(f),p=e("../util/decorate-service"),b=o(p),v="undefined"!=typeof document&&("onfocusin"in document?"focusin":"focus"),h="undefined"!=typeof document&&("onfocusin"in document?"focusout":"blur"),g=void 0,y=void 0,x=null,_=null,w={pointer:!1,key:!1,script:!1,initial:!1};n["default"]=b["default"]({engage:s,disengage:l}),t.exports=n["default"]},{"../event/shadow-focus":6,"../observe/interaction-type":46,"../util/decorate-service":114,"domtokenlist-shim/dist/domtokenlist-polyfill-umd":137}],68:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e||m["default"]();w.cssShadowPiercingDeepCombinator||(t=t.slice(-1));var n=[].slice.call(document.querySelectorAll(S),0),o=t.map(function(e){return b["default"]({context:e})}).reduce(function(e,t){return t.concat(e)},[]);n.forEach(function(e){-1===o.indexOf(e)&&e.classList&&e.classList.remove(O)}),o.forEach(function(e){-1===n.indexOf(e)&&e.classList&&e.classList.add(O)})}function u(){P=(window.setImmediate||window.setTimeout)(function(){r()})}function a(){(window.clearImmediate||window.clearTimeout)(P),r()}function i(e){r(e.detail.elements)}function l(){A&&A.disengage(),(window.clearImmediate||window.clearTimeout)(P),document.removeEventListener(E,u,!0),document.removeEventListener(M,a,!0),document.removeEventListener("shadow-focus",i,!0),[].forEach.call(document.querySelectorAll(S),function(e){e.classList.remove(O)})}function s(){w||(w=_["default"](),S=y["default"]("."+O)),A=c["default"](),document.addEventListener(E,u,!0),document.addEventListener(M,a,!0),document.addEventListener("shadow-focus",i,!0),r()}Object.defineProperty(n,"__esModule",{value:!0}),e("domtokenlist-shim/dist/domtokenlist-polyfill-umd");var d=e("../event/shadow-focus"),c=o(d),f=e("../get/active-elements"),m=o(f),p=e("../get/parents"),b=o(p),v=e("../util/decorate-service"),h=o(v),g=e("../util/select-in-shadows"),y=o(g),x=e("./focus-within.supports"),_=o(x),w=void 0,M="undefined"!=typeof document&&("onfocusin"in document?"focusin":"focus"),E="undefined"!=typeof document&&("onfocusin"in document?"focusout":"blur"),O="ally-focus-within",S=void 0,P=void 0,A=void 0;n["default"]=h["default"]({engage:s,disengage:l}),t.exports=n["default"]},{"../event/shadow-focus":6,"../get/active-elements":12,"../get/parents":17,"../util/decorate-service":114,"../util/select-in-shadows":124,"./focus-within.supports":69,"domtokenlist-shim/dist/domtokenlist-polyfill-umd":137}],69:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/memorize-result"),u=o(r),a=e("../supports/css-shadow-piercing-deep-combinator"),i=o(a);n["default"]=u["default"](function(){return{cssShadowPiercingDeepCombinator:i["default"]()}}),t.exports=n["default"]},{"../supports/css-shadow-piercing-deep-combinator":70,"../supports/memorize-result":107}],70:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./supports-cache"),u=o(r),a=e("./memorize-result"),i=o(a),l="supports-css-shadow-piercing-deep-combinator";n["default"]=i["default"](function(){var e=u["default"].get(l);try{document.querySelector("html >>> :first-child"),e=">>>"}catch(t){try{document.querySelector("html /deep/ :first-child"),e="/deep/"}catch(n){e=""}}return u["default"].set(l,e),e}),t.exports=n["default"]},{"./memorize-result":107,"./supports-cache":108}],71:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=document.createElement("div");t.setAttribute("style","position:fixed; position:absolute; top:0; left:-2px; width:1px; height:1px; overflow:hidden;"),t.setAttribute("aria-live","off"),t.setAttribute("aria-busy","true"),t.setAttribute("aria-hidden","true"),document.body.appendChild(t);var n="string"==typeof e.element?document.createElement(e.element):e.element(t),o=e.mutate&&e.mutate(n,t)||n;!n.parentNode&&t.appendChild(n);var r=document.activeElement,u=window.scrollTop,a=window.scrollLeft,i=document.body.scrollTop,l=document.body.scrollLeft;o.focus&&o.focus();var s=e.validate?e.validate(n):document.activeElement===o;return document.activeElement&&document.activeElement.blur(),r&&r.focus()||document.body.focus(),document.body.removeChild(t),window.scrollTop!==u&&(window.scrollTop=u),window.scrollLeft!==a&&(window.scrollLeft=a),document.body.scrollTop!==i&&(document.body.scrollTop=i),document.body.scrollLeft!==l&&(document.body.scrollLeft=l),s}Object.defineProperty(n,"__esModule",{value:!0});var u=e("./supports-cache"),a=o(u);n["default"]=function(e){var t=a["default"].get(e.name);return void 0===t&&(t=r(e),a["default"].set(e.name,t)),t},t.exports=n["default"]},{"./supports-cache":108}],72:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/gif"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-area-img-tabindex",element:"div",mutate:function(e){return e.innerHTML='<map name="image-map-tabindex-test"><area shape="rect" coords="63,19,144,45"></map><img usemap="#image-map-tabindex-test" tabindex="-1" alt="" src="'+s["default"]+'">',e.querySelector("area")}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/gif":103,"./memorize-result":107}],73:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/gif"),s=o(l),d=e("../util/platform"),c=o(d);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-area-tabindex",element:"div",mutate:function(e){return e.innerHTML='<map name="image-map-tabindex-test"><area href="#void" tabindex="-1" shape="rect" coords="63,19,144,45"></map><img usemap="#image-map-tabindex-test" alt="" src="'+s["default"]+'">',e.querySelector("area")},validate:function(e){if(c["default"].is.GECKO)return!0;var t=e.querySelector("area");return document.activeElement===t}})}),t.exports=n["default"]},{"../util/platform":123,"./detect-focus":71,"./media/gif":103,"./memorize-result":107}],74:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/gif"),s=o(l),d=e("../util/platform"),c=o(d);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-area-without-href",element:"div",mutate:function(e){return e.innerHTML='<map name="image-map-area-href-test"><area shape="rect" coords="63,19,144,45"></map><img usemap="#image-map-area-href-test" alt="" src="'+s["default"]+'">',e.querySelector("area")},validate:function(e){if(c["default"].is.GECKO)return!0;var t=e.querySelector("area");return document.activeElement===t}})}),t.exports=n["default"]},{"../util/platform":123,"./detect-focus":71,"./media/gif":103,"./memorize-result":107}],75:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/mp3"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-audio-without-controls",element:"audio",mutate:function(e){try{e.setAttribute("src",s["default"])}catch(t){}}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/mp3":104,"./memorize-result":107}],76:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/gif.invalid"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-broken-image-map",element:"div",mutate:function(e){return e.innerHTML='<map name="broken-image-map-test"><area href="#void" shape="rect" coords="63,19,144,45"></map><img usemap="#broken-image-map-test" alt="" src="'+s["default"]+'">',e.querySelector("area")}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/gif.invalid":102,"./memorize-result":107}],77:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-children-of-focusable-flexbox",element:"div",mutate:function(e){return e.setAttribute("tabindex","-1"),e.setAttribute("style","display: -webkit-flex; display: -ms-flexbox; display: flex;"),e.innerHTML='<span style="display: block;">hello</span>',e.querySelector("span")}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],78:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-disabled-fieldset",element:"fieldset",mutate:function(e){e.setAttribute("tabindex",0),e.setAttribute("disabled","disabled")}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],79:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-fieldset",element:"fieldset",mutate:function(e){e.innerHTML="<legend>legend</legend><p>content</p>"}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],80:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-flexbox-container",element:"span",mutate:function(e){e.setAttribute("style","display: -webkit-flex; display: -ms-flexbox; display: flex;"),e.innerHTML='<span style="display: block;">hello</span>'}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],81:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-disabled-form",element:"form",mutate:function(e){e.setAttribute("tabindex",0),e.setAttribute("disabled","disabled")}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],82:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/gif"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-img-ismap",element:"a",mutate:function(e){return e.href="#void",e.innerHTML='<img ismap src="'+s["default"]+'" alt="">',e.querySelector("img")}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/gif":103,"./memorize-result":107}],83:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/gif"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-img-usemap-tabindex",element:"div",mutate:function(e){return e.innerHTML='<map name="image-map-tabindex-test"><area href="#void" shape="rect" coords="63,19,144,45"></map><img usemap="#image-map-tabindex-test" tabindex="-1" alt="" src="'+s["default"]+'">',e.querySelector("img")}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/gif":103,"./memorize-result":107}],84:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=void 0;n["default"]=i["default"](function(){return u["default"]({name:"can-focus-in-hidden-iframe",element:function(e){var t=document.createElement("iframe");e.appendChild(t);var n=t.contentWindow;return l=n.document,t},mutate:function(e){e.style.visibility="hidden",l.open(),l.close();var t=l.createElement("input");return l.body.appendChild(t),l.querySelector("input")},validate:function(){var e=l.querySelector("input");return l.activeElement===e}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],85:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/platform"),u=o(r),a=!u["default"].is.WEBKIT;n["default"]=function(){return a},t.exports=n["default"]},{"../util/platform":123}],86:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"allows-invalid-tabindex-value",element:"div",mutate:function(e){e.setAttribute("tabindex","invalid-value")}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],87:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-label-tabindex",element:"label",mutate:function(e){e.setAttribute("tabindex","-1")},validate:function(e){e.offsetHeight;return e.focus(),document.activeElement===e}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],88:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/svg"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-object-svg-hidden",element:"object",mutate:function(e){e.setAttribute("type","image/svg+xml"),e.setAttribute("data",s["default"]),e.setAttribute("width","200"),e.setAttribute("height","50"),e.style.visibility="hidden"}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/svg":106,"./memorize-result":107}],89:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/svg"),s=o(l),d=e("../util/platform"),c=o(d);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-object-svg",element:"object",mutate:function(e){e.setAttribute("type","image/svg+xml"),e.setAttribute("data",s["default"]),e.setAttribute("width","200"),e.setAttribute("height","50")},validate:function(e){return c["default"].is.GECKO?!0:document.activeElement===e}})}),t.exports=n["default"]},{"../util/platform":123,"./detect-focus":71,"./media/svg":106,"./memorize-result":107}],90:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/platform"),u=o(r),a=!u["default"].is.TRIDENT||!u["default"].is.IE9;n["default"]=function(){return a},t.exports=n["default"]},{"../util/platform":123}],91:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/gif"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-redirect-img-usemap",element:"div",mutate:function(e){e.innerHTML='<map name="focus-redirect-img-usemap"><area href="#void" shape="rect" coords="63,19,144,45"></map><img usemap="#focus-redirect-img-usemap" alt="" src="'+s["default"]+'">'},validate:function(e){var t=e.querySelector("img"),n=e.querySelector("area");return t.focus(),document.activeElement===n}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/gif":103,"./memorize-result":107}],92:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-redirect-legend",element:"fieldset",mutate:function(e){e.innerHTML='<legend>legend</legend><input tabindex="-1"><input tabindex="0">'},validate:function(e){var t=e.querySelector("legend"),n=e.querySelector('input[tabindex="-1"]'),o=e.querySelector('input[tabindex="0"]');return t.focus(),document.activeElement===n&&"focusable"||document.activeElement===o&&"tabbable"||""}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],93:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-scroll-body",element:"div",mutate:function(e){return e.setAttribute("style","width: 100px; height: 50px; overflow: auto;"),e.innerHTML='<div style="width: 500px; height: 40px;">scrollable content</div>',e.querySelector("div")}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],94:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-scroll-container-without-overflow",element:"div",mutate:function(e){e.setAttribute("style","width: 100px; height: 50px;"),e.innerHTML='<div style="width: 500px; height: 40px;">scrollable content</div>'}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],95:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-scroll-container",element:"div",mutate:function(e){e.setAttribute("style","width: 100px; height: 50px; overflow: auto;"),e.innerHTML='<div style="width: 500px; height: 40px;">scrollable content</div>'}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],96:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-summary",element:"details",mutate:function(e){return e.innerHTML="<summary>foo</summary><p>content</p>",e.firstElementChild}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],97:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0}),e("../prototype/svgelement.prototype.focus");var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("../util/platform"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-svg-focusable-attribute",element:"div",mutate:function(e){return e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><text focusable="true">a</text></svg>',e.querySelector("text")},validate:function(e){var t=e.querySelector("text");return!s["default"].is.TRIDENT||t.focus&&"noop"!==t.focus._polyfill?document.activeElement===t:!0}})}),t.exports=n["default"]},{"../prototype/svgelement.prototype.focus":49,"../util/platform":123,"./detect-focus":71,"./memorize-result":107}],98:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("../util/platform"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-svg",element:"div",mutate:function(e){return e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>',e.firstChild},validate:function(e){var t=e.firstChild;return!s["default"].is.TRIDENT||t.focus&&"noop"!==t.focus._polyfill?document.activeElement===t:!0}})}),t.exports=n["default"]},{"../util/platform":123,"./detect-focus":71,"./memorize-result":107}],99:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"allows-tabindex-trailing-characters",element:"div",mutate:function(e){e.setAttribute("tabindex","3x")}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],100:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-table",element:"table",mutate:function(e){var t=document.createDocumentFragment();t.innerHTML="<tr><td>cell</td></tr>",e.appendChild(t)}})}),t.exports=n["default"]},{"./detect-focus":71,"./memorize-result":107}],101:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./detect-focus"),u=o(r),a=e("./memorize-result"),i=o(a),l=e("./media/mp4"),s=o(l);n["default"]=i["default"](function(){return u["default"]({name:"can-focus-video-without-controls",element:"video",mutate:function(e){try{e.setAttribute("src",s["default"])}catch(t){}}})}),t.exports=n["default"]},{"./detect-focus":71,"./media/mp4":105,"./memorize-result":107}],102:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",t.exports=n["default"]},{}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",t.exports=n["default"]},{}],104:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./gif"),u=o(r);n["default"]=u["default"],t.exports=n["default"]},{"./gif":103}],105:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./gif"),u=o(r);n["default"]=u["default"],t.exports=n["default"]},{"./gif":103}],106:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiBpZD0ic3ZnIj48dGV4dCB4PSIxMCIgeT0iMjAiIGlkPSJzdmctbGluay10ZXh0Ij50ZXh0PC90ZXh0Pjwvc3ZnPg==",t.exports=n["default"]},{}],107:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){var t=e;return function(){return t!==e?t:t=e()}},t.exports=n["default"]},{}],108:[function(e,t,n){
"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=void 0;try{t=window.localStorage&&window.localStorage.getItem(e),t=t?JSON.parse(t):{}}catch(n){t={}}return t}function u(e,t){if(document.hasFocus())try{window.localStorage&&window.localStorage.setItem(e,JSON.stringify(t))}catch(n){}else try{window.localStorage&&window.localStorage.removeItem(e)}catch(n){}}Object.defineProperty(n,"__esModule",{value:!0});var a=e("../version"),i=o(a),l="undefined"!=typeof window&&window.navigator.userAgent||"",s="ally-supports-cache",d=r(s);(d.userAgent!==l||d.version!==i["default"])&&(d={}),d.userAgent=l,d.version=i["default"],n["default"]={get:function(e){return d[e]},set:function(e,t){d[e]=t,u(s,d)}},t.exports=n["default"]},{"../version":129}],109:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o="undefined"!=typeof Element,r="undefined"!=typeof SVGElement,u=o&&r&&function(){return Boolean(SVGElement.prototype.focus&&!SVGElement.prototype.focus._polyfill)}();n["default"]=function(){return u},t.exports=n["default"]},{}],110:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/platform"),u=o(r),a=u["default"].is.GECKO||u["default"].is.TRIDENT;n["default"]=function(){return a},t.exports=n["default"]},{"../util/platform":123}],111:[function(e,t,n){"use strict";function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.parent,n=e.element,o=e.includeSelf;if(t)return function(e){return Boolean(o&&e===t||t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_CONTAINED_BY)};if(n)return function(e){return Boolean(o&&n===e||e.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_CONTAINED_BY)};throw new TypeError("util/compare-position#getParentComparator required either options.parent or options.element")}Object.defineProperty(n,"__esModule",{value:!0}),n.getParentComparator=o},{}],112:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../util/node-array"),u=o(r);n["default"]=function(e){var t=e.context,n=e.label,o=void 0===n?"context-to-element":n,r=e.resolveDocument,a=e.defaultToDocument,i=u["default"](t)[0];if(r&&i&&i.nodeType===Node.DOCUMENT_NODE&&(i=i.documentElement),!i&&a)return document.documentElement;if(!i)throw new TypeError(o+" requires valid options.context");if(i.nodeType!==Node.ELEMENT_NODE&&i.nodeType!==Node.DOCUMENT_FRAGMENT_NODE)throw new TypeError(o+" requires options.context to be an Element");return i},t.exports=n["default"]},{"../util/node-array":122}],113:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(){this.context&&(this.context.forEach(this.disengage),this.context=null,this.engage=null,this.disengage=null)}function u(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context;return this.context=l["default"](t||document),this.context.forEach(this.engage),{disengage:r.bind(this)}}function a(){}Object.defineProperty(n,"__esModule",{value:!0});var i=e("../util/node-array"),l=o(i);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.engage,n=e.disengage,o={engage:t||a,disengage:n||a,context:null};return u.bind(o)},t.exports=n["default"]},{"../util/node-array":122}],114:[function(e,t,n){"use strict";function o(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.force;t?this.instances=0:this.instances--,this.instances||(this.disengage(),this._result=null)}function r(){return this.instances?(this.instances++,this._result):(this.instances++,this._result=this.engage()||{},this._result.disengage=o.bind(this),this._result)}function u(){}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.engage,n=e.disengage,o={engage:t||u,disengage:n||u,instances:0,_result:null};return r.bind(o)},t.exports=n["default"]},{}],115:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){try{return e.contentDocument||e.contentWindow&&e.contentWindow.document||e.getSVGDocument&&e.getSVGDocument()||null}catch(t){return null}},t.exports=n["default"]},{}],116:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){return e?e.nodeType===Node.DOCUMENT_NODE?e:e.ownerDocument||document:document},t.exports=n["default"]},{}],117:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){if(f||(f=c["default"]("object, iframe")),void 0!==e._frameElement)return e._frameElement;e._frameElement=null;var t=e.parent.document.querySelectorAll(f);return[].some.call(t,function(t){var n=i["default"](t);return n!==e.document?!1:(e._frameElement=t,!0)}),e._frameElement}function u(e){var t=s["default"](e);if(!t.parent||t.parent===t)return null;try{return t.frameElement||r(t)}catch(n){return null}}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=u;var a=e("./get-content-document"),i=o(a),l=e("./get-window"),s=o(l),d=e("./select-in-shadows"),c=o(d),f=void 0;t.exports=n["default"]},{"./get-content-document":115,"./get-window":118,"./select-in-shadows":124}],118:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./get-document"),u=o(r);n["default"]=function(e){var t=u["default"](e);return t.defaultView||window},t.exports=n["default"]},{"./get-document":116}],119:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n=t.querySelector('map[name="'+l["default"](e)+'"]');return n||null}function u(e){var t=e.getAttribute("usemap");if(!t)return null;var n=d["default"](e);return r(t.slice(1),n)}function a(e){var t=e.parentElement;if(!t.name||"map"!==t.nodeName.toLowerCase())return null;var n=d["default"](e);return n.querySelector('img[usemap="#'+l["default"](t.name)+'"]')||null}Object.defineProperty(n,"__esModule",{value:!0}),n.getMapByName=r,n.getMapOfImage=u,n.getImageOfArea=a;var i=e("css.escape"),l=o(i),s=e("../util/get-document"),d=o(s)},{"../util/get-document":116,"css.escape":136}],120:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o=function(){},r={log:o,debug:o,info:o,warn:o,error:o};n["default"]="undefined"!=typeof console?console:r,t.exports=n["default"]},{}],121:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){return e.findIndex(function(e){return t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING})}function u(e,t,n){var o=[];return t.forEach(function(t){var u=!0,a=e.indexOf(t);-1===a&&(a=r(e,t),u=!1),-1===a&&(a=e.length);var i=l["default"](n?n(t):t);i.length&&o.push({offset:a,replace:u,elements:i})}),o}function a(e,t){var n=0;t.sort(function(e,t){return e.offset-t.offset}),t.forEach(function(t){var o=t.replace?1:0,r=[t.offset+n,o].concat(t.elements);e.splice.apply(e,r),n+=t.elements.length-o})}Object.defineProperty(n,"__esModule",{value:!0});var i=e("./node-array"),l=o(i),s=e("./sort-dom-order"),d=o(s);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.list,n=e.elements,o=e.resolveElement,r=t.slice(0),i=l["default"](n).slice(0);d["default"](i);var s=u(r,i,o);return a(r,s),r},t.exports=n["default"]},{"./node-array":122,"./sort-dom-order":125}],122:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){if(!e)return[];if(Array.isArray(e))return e;if(void 0!==e.nodeType)return[e];if("string"==typeof e&&(e=document.querySelectorAll(e)),void 0!==e.length)return[].slice.call(e,0);throw new TypeError("unexpected input "+String(e))},t.exports=n["default"]},{}],123:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("platform"),u=o(r),a=JSON.parse(JSON.stringify(u["default"])),i=a.os.family||"",l="Android"===i,s="Windows"===i.slice(0,7),d="OS X"===i,c="iOS"===i,f="Blink"===a.layout,m="Gecko"===a.layout,p="Trident"===a.layout,b="WebKit"===a.layout,v=parseFloat(a.version),h=Math.floor(v);a.majorVersion=h,a.is={ANDROID:l,WINDOWS:s,OSX:d,IOS:c,BLINK:f,GECKO:m,TRIDENT:p,WEBKIT:b,IE9:p&&9===h,IE10:p&&10===h,IE11:p&&11===h},n["default"]=a,t.exports=n["default"]},{platform:139}],124:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../supports/css-shadow-piercing-deep-combinator"),u=o(r),a=void 0;n["default"]=function(e){if("string"!=typeof a){var t=u["default"]();t&&(a=", html "+t+" ")}return a?e+a+e.replace(/\s*,\s*/g,",").split(",").join(a):e},t.exports=n["default"]},{"../supports/css-shadow-piercing-deep-combinator":70}],125:[function(e,t,n){"use strict";function o(e,t){return e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){return e.sort(o)},t.exports=n["default"]},{}],126:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("../is/valid-tabindex"),u=o(r);n["default"]=function(e){if(!u["default"](e))return null;var t=parseInt(e.getAttribute("tabindex"),10);return isNaN(t)?-1:t},t.exports=n["default"]},{"../is/valid-tabindex":35}],127:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){var t=e.element,n=e.attribute,o=e.temporaryValue,r=e.saveValue,u="data-cached-"+n;if(void 0!==o){var a=r||t.getAttribute(n);t.setAttribute(u,a||""),t.setAttribute(n,o)}else{var a=t.getAttribute(u);t.removeAttribute(u),""===a?t.removeAttribute(n):t.setAttribute(n,a)}},t.exports=n["default"]},{}],128:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n=Math.max(e.top,t.top),o=Math.max(e.left,t.left),r=Math.max(Math.min(e.right,t.right),o),u=Math.max(Math.min(e.bottom,t.bottom),n);return{top:n,right:r,bottom:u,left:o,width:r-o,height:u-n}}function u(){var e=window.innerWidth||document.documentElement.clientWidth,t=window.innerHeight||document.documentElement.clientHeight;return{top:0,right:e,bottom:t,left:0,width:e,height:t}}function a(e){var t=e.getBoundingClientRect(),n=e.offsetWidth-e.clientWidth,o=e.offsetHeight-e.clientHeight,r={top:t.top,left:t.left,right:t.right-n,bottom:t.bottom-o,width:t.width-n,height:t.height-o,area:0};return r.area=r.width*r.height,r}function i(e){var t=window.getComputedStyle(e,null),n="visible";return t.getPropertyValue("overflow-x")!==n&&t.getPropertyValue("overflow-y")!==n}function l(e){return i(e)?e.offsetHeight<e.scrollHeight||e.offsetWidth<e.scrollWidth:!1}function s(e){var t=c["default"]({context:e}).slice(1).filter(l);return t.length?t.reduce(function(e,t){var n=a(t),o=r(n,e);return o.area=Math.min(n.area,e.area),o},a(t[0])):null}Object.defineProperty(n,"__esModule",{value:!0});var d=e("../get/parents"),c=o(d);n["default"]=function(e){var t=e.getBoundingClientRect(),n=u();n.area=n.width*n.height;var o=n,a=s(e);if(a){if(!a.width||!a.height)return 0;o=r(a,n),o.area=a.area}var i=r(t,o);if(!i.width||!i.height)return 0;var l=t.width*t.height,d=Math.min(l,o.area),c=Math.round(i.width)*Math.round(i.height)/d,f=1e4;return Math.round(c*f)/f},t.exports=n["default"]},{"../get/parents":17}],129:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o="1.1.1";n["default"]=o,t.exports=n["default"]},{}],130:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./focusable"),u=o(r),a=e("./key"),i=o(a),l=e("./visible-area"),s=o(l);n["default"]={focusable:u["default"],key:i["default"],visibleArea:s["default"]},t.exports=n["default"]},{"./focusable":131,"./key":133,"./visible-area":134}],131:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./visible-area"),u=o(r),a=e("../is/focusable"),i=o(a),l=e("../util/context-to-element"),s=o(l),d=e("../util/get-document"),c=o(d);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.callback,o=e.area;if("function"!=typeof n)throw new TypeError("when/focusable requires options.callback to be a function");var r=s["default"]({label:"when/focusable",context:t}),a=function(e){return i["default"](e)?n(e):!1},l=c["default"](r),d=u["default"]({context:r,callback:a,area:o}),f=function m(){l.removeEventListener("focus",m,!0),d&&d.disengage()};return l.addEventListener("focus",f,!0),{disengage:f}},t.exports=n["default"]},{"../is/focusable":26,"../util/context-to-element":112,"../util/get-document":116,"./visible-area":134}],132:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e?null:!1;return{altKey:t,ctrlKey:t,metaKey:t,shiftKey:t}}function u(e){var t=-1!==e.indexOf("*"),n=r(t);return e.forEach(function(e){if("*"!==e){var t=!0,o=e.slice(0,1);"?"===o?t=null:"!"===o&&(t=!1),t!==!0&&(e=e.slice(1));var r=d[e];if(!r)throw new TypeError('Unknown modifier "'+e+'"');n[r]=t}}),n}function a(e){var t=s["default"][e]||parseInt(e,10);if(!t||"number"!=typeof t||isNaN(t))throw new TypeError('Unknown key "'+e+'"');return[t].concat(s["default"]._alias[t]||[])}function i(e,t){return!c.some(function(n){return"boolean"==typeof e[n]&&Boolean(t[n])!==e[n]})}Object.defineProperty(n,"__esModule",{value:!0});var l=e("../map/keycode"),s=o(l),d={alt:"altKey",ctrl:"ctrlKey",meta:"metaKey",shift:"shiftKey"},c=Object.keys(d).map(function(e){return d[e]});n["default"]=function(e){return e.split(/\s+/).map(function(e){var t=e.split("+"),n=u(t.slice(0,-1)),o=a(t.slice(-1));return{keyCodes:o,modifiers:n,matchModifiers:i.bind(null,n)}})},t.exports=n["default"]},{"../map/keycode":44}],133:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./key.binding"),u=o(r),a=e("../util/node-array"),i=o(a),l=e("../util/compare-position");n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=void 0,n={},o=i["default"](e.context)[0]||document.documentElement;delete e.context;var r=i["default"](e.filter);delete e.filter;var a=Object.keys(e);if(!a.length)throw new TypeError("when/key requires at least one option key");var s=function(e){e.keyCodes.forEach(function(t){n[t]||(n[t]=[]),n[t].push(e)})};a.forEach(function(t){if("function"!=typeof e[t])throw new TypeError('when/key requires option["'+t+'"] to be a function');var n=function(n){return n.callback=e[t],n};u["default"](t).map(n).forEach(s)});var d=function(e){if(!e.defaultPrevented){if(r.length){var u=l.getParentComparator({element:e.target,includeSelf:!0});if(r.some(u))return}var a=e.keyCode||e.which;n[a]&&n[a].forEach(function(n){n.matchModifiers(e)&&n.callback.call(o,e,t)})}};return o.addEventListener("keydown",d,!1),t=function(){o.removeEventListener("keydown",d,!1)},{disengage:t}},t.exports=n["default"]},{"../util/compare-position":111,"../util/node-array":122,"./key.binding":132}],134:[function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0}),e("../prototype/window.requestanimationframe");var r=e("../is/visible"),u=o(r),a=e("../util/visible-area"),i=o(a),l=e("../util/context-to-element"),s=o(l);n["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.context,n=e.callback,o=e.area;if("function"!=typeof n)throw new TypeError("when/visible-area requires options.callback to be a function");"number"!=typeof o&&(o=1);var r=s["default"]({label:"when/visible-area",context:t});if(u["default"](r)&&i["default"](r)>=o&&n(r)!==!1)return null;var a=void 0,l=function(){a&&cancelAnimationFrame(a)},d=function c(){return!u["default"](r)||i["default"](r)<o||n(r)===!1?void(a=requestAnimationFrame(c)):void l()};return d(),{disengage:l}},t.exports=n["default"]},{"../is/visible":37,"../prototype/window.requestanimationframe":51,"../util/context-to-element":112,"../util/visible-area":128}],135:[function(){!function(){if(!Array.prototype.findIndex){var e=function(e){var t=Object(this),n=Math.max(0,t.length)>>>0;if(0===n)return-1;if("function"!=typeof e||"[object Function]"!==Object.prototype.toString.call(e))throw new TypeError("Array#findIndex: predicate must be a function");for(var o=arguments.length>1?arguments[1]:void 0,r=0;n>r;r++)if(e.call(o,t[r],r,t))return r;return-1};if(Object.defineProperty)try{Object.defineProperty(Array.prototype,"findIndex",{value:e,configurable:!0,writable:!0})}catch(t){}Array.prototype.findIndex||(Array.prototype.findIndex=e)}}(this)},{}],136:[function(t,n,o){(function(t){!function(t,r){"object"==typeof o?n.exports=r(t):"function"==typeof e&&e.amd?e([],r.bind(t,t)):r(t)}("undefined"!=typeof t?t:this,function(e){if(e.CSS&&e.CSS.escape)return e.CSS.escape;var t=function(e){for(var t,n=String(e),o=n.length,r=-1,u="",a=n.charCodeAt(0);++r<o;)t=n.charCodeAt(r),u+=0!=t?t>=1&&31>=t||127==t||0==r&&t>=48&&57>=t||1==r&&t>=48&&57>=t&&45==a?"\\"+t.toString(16)+" ":(0!=r||1!=o||45!=t)&&(t>=128||45==t||95==t||t>=48&&57>=t||t>=65&&90>=t||t>=97&&122>=t)?n.charAt(r):"\\"+n.charAt(r):"�";return u};return e.CSS||(e.CSS={}),e.CSS.escape=t,t})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],137:[function(t,n,o){!function(r,u){"function"==typeof e&&e.amd?e(["./domtokenlist-umd"],u):"object"==typeof o?n.exports=u(t("./domtokenlist-umd")):r.DOMTokenList=u(r.DOMTokenList)}(this,function(e){return"undefined"!=typeof window&&function(t){"use strict";if(t.DOMTokenList){var n=document.createElement("a").classList,o=e.prototype,r=o.add,u=o.remove,a=o.toggle;n.add("c1","c2");var i=function(e){return function(){var t,n=arguments;for(t=0;t<n.length;t+=1)e.call(this,n[t])}};n.contains("c2")||(o.add=i(r),o.remove=i(u)),n.toggle("c1",!0)||(o.toggle=function(e,t){return void 0===t?a.call(this,e):((t?r:u).call(this,e),!!t)})}}(window),"undefined"!=typeof window&&function(){"use strict";"classList"in document.createElement("a")&&!window.QUnit||Object.defineProperty(Element.prototype,"classList",{get:function(){return new e(this,"className")}})}(),"undefined"!=typeof window&&function(){"use strict";if(!("relList"in document.createElement("a"))||window.QUnit){var t,n=[HTMLAnchorElement,HTMLAreaElement,HTMLLinkElement],o=function(){return new e(this,"rel")};for(t=0;t<n.length;t++)Object.defineProperty(n[t].prototype,"relList",{get:o})}}(),"undefined"!=typeof window&&function(){"use strict";var t=document.createElementNS("http://www.w3.org/2000/svg","svg");"classList"in t&&!window.QUnit||Object.defineProperty(SVGElement.prototype,"classList",{get:function(){return"string"==typeof this.className?new e(this,"className"):"string"==typeof this.className.baseVal?new e(this.className,"baseVal"):void 0}})}(),"undefined"!=typeof window&&(window.DOMTokenList=e),e})},{"./domtokenlist-umd":138}],138:[function(t,n,o){!function(t,r){"function"==typeof e&&e.amd?e([],r):"object"==typeof o?n.exports=r():t.DOMTokenList=r()}(this,function(){"use strict";var e=[],t=function(t,n){var o;if(e.indexOf)return e.indexOf.call(t,n);for(o=0;o<t.length;o++)if(t[o]===n)return o;return-1},n=function(e){var t=/[\u0009\u000A\u000C\u000D\u0020]/;if(""===e||t.test(e))throw new Error("Token must not be empty or contain whitespace.")},o=function(e,t){var n,o=this,r=[];if(e&&t&&(o.element=e,o.prop=t,e[t]))for(r=e[t].replace(/^\s+|\s+$/g,"").split(/\s+/),n=0;n<r.length;n++)o[n]=r[n];o.length=r.length};return o.prototype={add:function(){var t,o=this,r=arguments;for(t=0;t<r.length;t++)n(r[t]),o.contains(r[t])||e.push.call(o,r[t]);o.element&&(o.element[o.prop]=o)},contains:function(e){return n(e),-1!==t(this,e)},item:function(e){return this[e]||null},remove:function(){var o,r,u=arguments,a=this;for(r=0;r<u.length;r++)n(u[r]),o=t(a,u[r]),-1!==o&&e.splice.call(a,o,1);a.element&&(a.element[a.prop]=a)},toggle:function(e,t){var n=this;return n.contains(e)?t?!0:(n.remove(e),!1):t===!1?!1:(n.add(e),!0)},toString:function(){return e.join.call(this," ")}},o})},{}],139:[function(t,n,o){(function(t){(function(){"use strict";function r(e){return e=String(e),e.charAt(0).toUpperCase()+e.slice(1)}function u(e,t,n){var o={6.4:"10",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};return t&&n&&/^Win/i.test(e)&&(o=o[/[\d.]+$/.exec(e)])&&(e="Windows "+o),e=String(e),t&&n&&(e=e.replace(RegExp(t,"i"),n)),e=i(e.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").split(" on ")[0])}function a(e,t){var n=-1,o=e?e.length:0;if("number"==typeof o&&o>-1&&_>=o)for(;++n<o;)t(e[n],n,e);else l(e,t)}function i(e){return e=m(e),/^(?:webOS|i(?:OS|P))/.test(e)?e:r(e)}function l(e,t){for(var n in e)O.call(e,n)&&t(e[n],n,e)}function s(e){return null==e?r(e):S.call(e).slice(8,-1)}function d(e,t){var n=null!=e?typeof e[t]:"number";return!/^(?:boolean|number|string|undefined)$/.test(n)&&("object"==n?!!e[t]:!0)}function c(e){return String(e).replace(/([ -])(?!$)/g,"$1?")}function f(e,t){var n=null;return a(e,function(o,r){n=t(n,o,r,e)}),n}function m(e){return String(e).replace(/^ +| +$/g,"")}function p(e){function t(t){return f(t,function(t,n){return t||RegExp("\\b"+(n.pattern||c(n))+"\\b","i").exec(e)&&(n.label||n)})}function n(t){return f(t,function(t,n,o){return t||(n[$]||n[/^[a-z]+(?: +[a-z]+\b)*/i.exec($)]||RegExp("\\b"+c(o)+"(?:\\b|\\w*\\d)","i").exec(e))&&o})}function o(t){return f(t,function(t,n){return t||RegExp("\\b"+(n.pattern||c(n))+"\\b","i").exec(e)&&(n.label||n)})}function r(t){return f(t,function(t,n){var o=n.pattern||c(n);return!t&&(t=RegExp("\\b"+o+"(?:/[\\d.]+|[ \\w.]*)","i").exec(e))&&(t=u(t,o,n.label||n)),t})}function a(t){return f(t,function(t,n){var o=n.pattern||c(n);return!t&&(t=RegExp("\\b"+o+" *\\d+[.\\w_]*","i").exec(e)||RegExp("\\b"+o+"(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)","i").exec(e))&&((t=String(n.label&&!RegExp(o,"i").test(n.label)?n.label:t).split("/"))[1]&&!/[\d.]+/.test(t[0])&&(t[0]+=" "+t[1]),n=n.label||n,t=i(t[0].replace(RegExp(o,"i"),n).replace(RegExp("; *(?:"+n+"[_-])?","i")," ").replace(RegExp("("+n+")[-_.]?(\\w)","i"),"$1 $2"))),t})}function b(t){return f(t,function(t,n){return t||(RegExp(n+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(e)||0)[1]||null})}function g(){return this.description||""}var y=v,x=e&&"object"==typeof e&&"String"!=s(e);x&&(y=e,e=null);var _=y.navigator||{},E=_.userAgent||"";e||(e=E);var O,P,A=x||M==h,T=x?!!_.likeChrome:/\bChrome\b/.test(e)&&!/internal|\n/i.test(S.toString()),j="Object",C=x?j:"ScriptBridgingProxyObject",I=x?j:"Environment",k=x&&y.java?"JavaPackage":s(y.java),F=x?j:"RuntimeObject",L=/\bJava/.test(k)&&y.java,N=L&&s(y.environment)==I,D=L?"a":"α",q=L?"b":"β",R=y.document||{},B=y.operamini||y.opera,z=w.test(z=x&&B?B["[[Class]]"]:s(B))?z:B=null,W=e,H=[],G=null,V=e==E,K=V&&B&&"function"==typeof B.version&&B.version(),Z=t(["Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"]),U=o(["Adobe AIR","Arora","Avant Browser","Breach","Camino","Epiphany","Fennec","Flock","Galeon","GreenBrowser","iCab","Iceweasel",{label:"SRWare Iron",pattern:"Iron"},"K-Meleon","Konqueror","Lunascape","Maxthon","Midori","Nook Browser","PhantomJS","Raven","Rekonq","RockMelt","SeaMonkey",{label:"Silk",pattern:"(?:Cloud9|Silk-Accelerated)"},"Sleipnir","SlimBrowser","Sunrise","Swiftfox","WebPositive","Opera Mini",{label:"Opera Mini",pattern:"OPiOS"},"Opera",{label:"Opera",pattern:"OPR"},"Chrome",{label:"Chrome Mobile",pattern:"(?:CriOS|CrMo)"},{label:"Firefox",pattern:"(?:Firefox|Minefield)"},{label:"IE",pattern:"IEMobile"},{label:"IE",pattern:"MSIE"},"Safari"]),$=a([{label:"BlackBerry",pattern:"BB10"},"BlackBerry",{label:"Galaxy S",pattern:"GT-I9000"},{label:"Galaxy S2",pattern:"GT-I9100"},{label:"Galaxy S3",pattern:"GT-I9300"},{label:"Galaxy S4",pattern:"GT-I9500"},"Google TV","Lumia","iPad","iPod","iPhone","Kindle",{label:"Kindle Fire",pattern:"(?:Cloud9|Silk-Accelerated)"},"Nook","PlayBook","PlayStation 4","PlayStation 3","PlayStation Vita","TouchPad","Transformer",{label:"Wii U",pattern:"WiiU"},"Wii","Xbox One",{label:"Xbox 360",pattern:"Xbox"},"Xoom"]),X=n({Apple:{iPad:1,iPhone:1,iPod:1},Amazon:{Kindle:1,"Kindle Fire":1},Asus:{Transformer:1},"Barnes & Noble":{Nook:1},BlackBerry:{PlayBook:1},Google:{"Google TV":1},HP:{TouchPad:1},HTC:{},LG:{},Microsoft:{Xbox:1,"Xbox One":1},Motorola:{Xoom:1},Nintendo:{"Wii U":1,Wii:1},Nokia:{Lumia:1},Samsung:{"Galaxy S":1,"Galaxy S2":1,"Galaxy S3":1,"Galaxy S4":1},Sony:{"PlayStation 4":1,"PlayStation 3":1,"PlayStation Vita":1}}),J=r(["Windows Phone ","Android","CentOS","Debian","Fedora","FreeBSD","Gentoo","Haiku","Kubuntu","Linux Mint","Red Hat","SuSE","Ubuntu","Xubuntu","Cygwin","Symbian OS","hpwOS","webOS ","webOS","Tablet OS","Linux","Mac OS X","Macintosh","Mac","Windows 98;","Windows "]);if(Z&&(Z=[Z]),X&&!$&&($=a([X])),(O=/\bGoogle TV\b/.exec($))&&($=O[0]),/\bSimulator\b/i.test(e)&&($=($?$+" ":"")+"Simulator"),"Opera Mini"==U&&/\bOPiOS\b/.test(e)&&H.push("running in Turbo/Uncompressed mode"),/^iP/.test($)?(U||(U="Safari"),J="iOS"+((O=/ OS ([\d_]+)/i.exec(e))?" "+O[1].replace(/_/g,"."):"")):"Konqueror"!=U||/buntu/i.test(J)?X&&"Google"!=X&&(/Chrome/.test(U)&&!/\bMobile Safari\b/i.test(e)||/\bVita\b/.test($))?(U="Android Browser",J=/\bAndroid\b/.test(J)?J:"Android"):(!U||(O=!/\bMinefield\b|\(Android;/i.test(e)&&/\b(?:Firefox|Safari)\b/.exec(U)))&&(U&&!$&&/[\/,]|^[^(]+?\)/.test(e.slice(e.indexOf(O+"/")+8))&&(U=null),(O=$||X||J)&&($||X||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(J))&&(U=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(J)?J:O)+" Browser")):J="Kubuntu",(O=/\((Mobile|Tablet).*?Firefox\b/i.exec(e))&&O[1]&&(J="Firefox OS",$||($=O[1])),K||(K=b(["(?:Cloud9|CriOS|CrMo|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|Silk(?!/[\\d.]+$))","Version",c(U),"(?:Firefox|Minefield|NetFront)"])),"iCab"==Z&&parseFloat(K)>3?Z=["WebKit"]:"Trident"!=Z&&(O=/\bOpera\b/.test(U)&&(/\bOPR\b/.test(e)?"Blink":"Presto")||/\b(?:Midori|Nook|Safari)\b/i.test(e)&&"WebKit"||!Z&&/\bMSIE\b/i.test(e)&&("Mac OS"==J?"Tasman":"Trident"))?Z=[O]:/\bPlayStation\b(?! Vita\b)/i.test(U)&&"WebKit"==Z&&(Z=["NetFront"]),"IE"==U&&(O=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(e)||0)[1])?(U+=" Mobile",J="Windows Phone "+(/\+$/.test(O)?O:O+".x"),H.unshift("desktop mode")):/\bWPDesktop\b/i.test(e)?(U="IE Mobile",J="Windows Phone 8+",H.unshift("desktop mode"),K||(K=(/\brv:([\d.]+)/.exec(e)||0)[1])):"IE"!=U&&"Trident"==Z&&(O=/\brv:([\d.]+)/.exec(e))?(/\bWPDesktop\b/i.test(e)||(U&&H.push("identifying as "+U+(K?" "+K:"")),U="IE"),K=O[1]):"Chrome"!=U&&"IE"==U||!(O=/\bEdge\/([\d.]+)/.exec(e))||(U="Microsoft Edge",K=O[1],Z=["Trident"]),V){if(d(y,"global"))if(L&&(O=L.lang.System,W=O.getProperty("os.arch"),J=J||O.getProperty("os.name")+" "+O.getProperty("os.version")),A&&d(y,"system")&&(O=[y.system])[0]){J||(J=O[0].os||null);try{O[1]=y.require("ringo/engine").version,K=O[1].join("."),U="RingoJS"}catch(Q){O[0].global.system==y.system&&(U="Narwhal")}}else"object"==typeof y.process&&(O=y.process)?(U="Node.js",W=O.arch,J=O.platform,K=/[\d.]+/.exec(O.version)[0]):N&&(U="Rhino");else s(O=y.runtime)==C?(U="Adobe AIR",J=O.flash.system.Capabilities.os):s(O=y.phantom)==F?(U="PhantomJS",K=(O=O.version||null)&&O.major+"."+O.minor+"."+O.patch):"number"==typeof R.documentMode&&(O=/\bTrident\/(\d+)/i.exec(e))&&(K=[K,R.documentMode],(O=+O[1]+4)!=K[1]&&(H.push("IE "+K[1]+" mode"),Z&&(Z[1]=""),K[1]=O),K="IE"==U?String(K[1].toFixed(1)):K[0]);J=J&&i(J)}K&&(O=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(K)||/(?:alpha|beta)(?: ?\d)?/i.exec(e+";"+(V&&_.appMinorVersion))||/\bMinefield\b/i.test(e)&&"a")&&(G=/b/i.test(O)?"beta":"alpha",K=K.replace(RegExp(O+"\\+?$"),"")+("beta"==G?q:D)+(/\d+\+?/.exec(O)||"")),"Fennec"==U||"Firefox"==U&&/\b(?:Android|Firefox OS)\b/.test(J)?U="Firefox Mobile":"Maxthon"==U&&K?K=K.replace(/\.[\d.]+/,".x"):"Silk"==U?(/\bMobi/i.test(e)||(J="Android",H.unshift("desktop mode")),/Accelerated *= *true/i.test(e)&&H.unshift("accelerated")):/\bXbox\b/i.test($)?(J=null,"Xbox 360"==$&&/\bIEMobile\b/.test(e)&&H.unshift("mobile mode")):!/^(?:Chrome|IE|Opera)$/.test(U)&&(!U||$||/Browser|Mobi/.test(U))||"Windows CE"!=J&&!/Mobi/i.test(e)?"IE"==U&&V&&null===y.external?H.unshift("platform preview"):(/\bBlackBerry\b/.test($)||/\bBB10\b/.test(e))&&(O=(RegExp($.replace(/ +/g," *")+"/([.\\d]+)","i").exec(e)||0)[1]||K)?(O=[O,/BB10/.test(e)],J=(O[1]?($=null,X="BlackBerry"):"Device Software")+" "+O[0],K=null):this!=l&&"Wii"!=$&&(V&&B||/Opera/.test(U)&&/\b(?:MSIE|Firefox)\b/i.test(e)||"Firefox"==U&&/\bOS X (?:\d+\.){2,}/.test(J)||"IE"==U&&(J&&!/^Win/.test(J)&&K>5.5||/\bWindows XP\b/.test(J)&&K>8||8==K&&!/\bTrident\b/.test(e)))&&!w.test(O=p.call(l,e.replace(w,"")+";"))&&O.name&&(O="ing as "+O.name+((O=O.version)?" "+O:""),w.test(U)?(/\bIE\b/.test(O)&&"Mac OS"==J&&(J=null),O="identify"+O):(O="mask"+O,U=z?i(z.replace(/([a-z])([A-Z])/g,"$1 $2")):"Opera",/\bIE\b/.test(O)&&(J=null),V||(K=null)),Z=["Presto"],H.push(O)):U+=" Mobile",(O=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(e)||0)[1])&&(O=[parseFloat(O.replace(/\.(\d)$/,".0$1")),O],"Safari"==U&&"+"==O[1].slice(-1)?(U="WebKit Nightly",G="alpha",K=O[1].slice(0,-1)):(K==O[1]||K==(O[2]=(/\bSafari\/([\d.]+\+?)/i.exec(e)||0)[1]))&&(K=null),O[1]=(/\bChrome\/([\d.]+)/i.exec(e)||0)[1],537.36==O[0]&&537.36==O[2]&&parseFloat(O[1])>=28&&"IE"!=U&&"Microsoft Edge"!=U&&(Z=["Blink"]),V&&(T||O[1])?(Z&&(Z[1]="like Chrome"),O=O[1]||(O=O[0],530>O?1:532>O?2:532.05>O?3:533>O?4:534.03>O?5:534.07>O?6:534.1>O?7:534.13>O?8:534.16>O?9:534.24>O?10:534.3>O?11:535.01>O?12:535.02>O?"13+":535.07>O?15:535.11>O?16:535.19>O?17:536.05>O?18:536.1>O?19:537.01>O?20:537.11>O?"21+":537.13>O?23:537.18>O?24:537.24>O?25:537.36>O?26:"Blink"!=Z?"27":"28")):(Z&&(Z[1]="like Safari"),O=O[0],O=400>O?1:500>O?2:526>O?3:533>O?4:534>O?"4+":535>O?5:537>O?6:538>O?7:601>O?8:"8"),Z&&(Z[1]+=" "+(O+="number"==typeof O?".x":/[.+]/.test(O)?"":"+")),"Safari"==U&&(!K||parseInt(K)>45)&&(K=O)),"Opera"==U&&(O=/\bzbov|zvav$/.exec(J))?(U+=" ",H.unshift("desktop mode"),"zvav"==O?(U+="Mini",K=null):U+="Mobile",J=J.replace(RegExp(" *"+O+"$"),"")):"Safari"==U&&/\bChrome\b/.exec(Z&&Z[1])&&(H.unshift("desktop mode"),U="Chrome Mobile",K=null,/\bOS X\b/.test(J)?(X="Apple",J="iOS 4.3+"):J=null),K&&0==K.indexOf(O=/[\d.]+$/.exec(J))&&e.indexOf("/"+O+"-")>-1&&(J=m(J.replace(O,""))),Z&&!/\b(?:Avant|Nook)\b/.test(U)&&(/Browser|Lunascape|Maxthon/.test(U)||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(U)&&Z[1])&&(O=Z[Z.length-1])&&H.push(O),H.length&&(H=["("+H.join("; ")+")"]),X&&$&&$.indexOf(X)<0&&H.push("on "+X),$&&H.push((/^on /.test(H[H.length-1])?"":"on ")+$),J&&(O=/ ([\d.+]+)$/.exec(J),P=O&&"/"==J.charAt(J.length-O[0].length-1),J={architecture:32,family:O&&!P?J.replace(O[0],""):J,version:O?O[1]:null,toString:function(){var e=this.version;return this.family+(e&&!P?" "+e:"")+(64==this.architecture?" 64-bit":"")}}),(O=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(W))&&!/\bi686\b/i.test(W)&&(J&&(J.architecture=64,J.family=J.family.replace(RegExp(" *"+O),"")),U&&(/\bWOW64\b/i.test(e)||V&&/\w(?:86|32)$/.test(_.cpuClass||_.platform)&&!/\bWin64; x64\b/i.test(e))&&H.unshift("32-bit")),e||(e=null);var Y={};return Y.description=e,Y.layout=Z&&Z[0],Y.manufacturer=X,Y.name=U,Y.prerelease=G,Y.product=$,
Y.ua=e,Y.version=U&&K,Y.os=J||{architecture:null,family:null,version:null,toString:function(){return"null"}},Y.parse=p,Y.toString=g,Y.version&&H.unshift(K),Y.name&&H.unshift(U),J&&U&&(J!=String(J).split(" ")[0]||J!=U.split(" ")[0]&&!$)&&H.push($?"("+J+")":"on "+J),H.length&&(Y.description=H.join(" ")),Y}var b={"function":!0,object:!0},v=b[typeof window]&&window||this,h=v,g=b[typeof o]&&o,y=b[typeof n]&&n&&!n.nodeType&&n,x=g&&y&&"object"==typeof t&&t;!x||x.global!==x&&x.window!==x&&x.self!==x||(v=x);var _=Math.pow(2,53)-1,w=/\bOpera/,M=this,E=Object.prototype,O=E.hasOwnProperty,S=E.toString;"function"==typeof e&&"object"==typeof e.amd&&e.amd?e(function(){return p()}):g&&y?l(p(),function(e,t){g[t]=e}):v.platform=p()}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1])(1)});
//# sourceMappingURL=ally.min.js.map | dakshshah96/cdnjs | ajax/libs/ally.js/1.1.1/ally.min.js | JavaScript | mit | 129,064 |
/*!
* headroom.js v0.7.0 - Give your page some headroom. Hide your header until you need it
* Copyright (c) 2015 Nick Williams - http://wicky.nillia.ms/headroom.js
* License: MIT
*/
!function(a,b){"use strict";"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?module.exports=b():a.Headroom=b()}(this,function(){"use strict";function a(a){this.callback=a,this.ticking=!1}function b(a){return a&&"undefined"!=typeof window&&(a===window||a.nodeType)}function c(a){if(arguments.length<=0)throw new Error("Missing arguments in extend function");var d,e,f=a||{};for(e=1;e<arguments.length;e++){var g=arguments[e]||{};for(d in g)"object"!=typeof f[d]||b(f[d])?f[d]=f[d]||g[d]:f[d]=c(f[d],g[d])}return f}function d(a){return a===Object(a)?a:{down:a,up:a}}function e(b,f){f=c(f,e.options),this.lastKnownScrollY=0,this.elem=b,this.debouncer=new a(this.update.bind(this)),this.tolerance=d(f.tolerance),this.classes=f.classes,this.offset=f.offset,this.scroller=f.scroller,this.initialised=!1,this.onPin=f.onPin,this.onUnpin=f.onUnpin,this.onTop=f.onTop,this.onNotTop=f.onNotTop}var f={bind:!!function(){}.bind,classList:"classList"in document.documentElement,rAF:!!(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame)};return window.requestAnimationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame,a.prototype={constructor:a,update:function(){this.callback&&this.callback(),this.ticking=!1},requestTick:function(){this.ticking||(requestAnimationFrame(this.rafCallback||(this.rafCallback=this.update.bind(this))),this.ticking=!0)},handleEvent:function(){this.requestTick()}},e.prototype={constructor:e,init:function(){return e.cutsTheMustard?(this.elem.classList.add(this.classes.initial),setTimeout(this.attachEvent.bind(this),100),this):void 0},destroy:function(){var a=this.classes;this.initialised=!1,this.elem.classList.remove(a.unpinned,a.pinned,a.top,a.initial),this.scroller.removeEventListener("scroll",this.debouncer,!1)},attachEvent:function(){this.initialised||(this.lastKnownScrollY=this.getScrollY(),this.initialised=!0,this.scroller.addEventListener("scroll",this.debouncer,!1),this.debouncer.handleEvent())},unpin:function(){var a=this.elem.classList,b=this.classes;(a.contains(b.pinned)||!a.contains(b.unpinned))&&(a.add(b.unpinned),a.remove(b.pinned),this.onUnpin&&this.onUnpin.call(this))},pin:function(){var a=this.elem.classList,b=this.classes;a.contains(b.unpinned)&&(a.remove(b.unpinned),a.add(b.pinned),this.onPin&&this.onPin.call(this))},top:function(){var a=this.elem.classList,b=this.classes;a.contains(b.top)||(a.add(b.top),a.remove(b.notTop),this.onTop&&this.onTop.call(this))},notTop:function(){var a=this.elem.classList,b=this.classes;a.contains(b.notTop)||(a.add(b.notTop),a.remove(b.top),this.onNotTop&&this.onNotTop.call(this))},getScrollY:function(){return void 0!==this.scroller.pageYOffset?this.scroller.pageYOffset:void 0!==this.scroller.scrollTop?this.scroller.scrollTop:(document.documentElement||document.body.parentNode||document.body).scrollTop},getViewportHeight:function(){return window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight},getDocumentHeight:function(){var a=document.body,b=document.documentElement;return Math.max(a.scrollHeight,b.scrollHeight,a.offsetHeight,b.offsetHeight,a.clientHeight,b.clientHeight)},getElementHeight:function(a){return Math.max(a.scrollHeight,a.offsetHeight,a.clientHeight)},getScrollerHeight:function(){return this.scroller===window||this.scroller===document.body?this.getDocumentHeight():this.getElementHeight(this.scroller)},isOutOfBounds:function(a){var b=0>a,c=a+this.getViewportHeight()>this.getScrollerHeight();return b||c},toleranceExceeded:function(a,b){return Math.abs(a-this.lastKnownScrollY)>=this.tolerance[b]},shouldUnpin:function(a,b){var c=a>this.lastKnownScrollY,d=a>=this.offset;return c&&d&&b},shouldPin:function(a,b){var c=a<this.lastKnownScrollY,d=a<=this.offset;return c&&b||d},update:function(){var a=this.getScrollY(),b=a>this.lastKnownScrollY?"down":"up",c=this.toleranceExceeded(a,b);this.isOutOfBounds(a)||(a<=this.offset?this.top():this.notTop(),this.shouldUnpin(a,c)?this.unpin():this.shouldPin(a,c)&&this.pin(),this.lastKnownScrollY=a)}},e.options={tolerance:{up:0,down:0},offset:0,scroller:window,classes:{pinned:"headroom--pinned",unpinned:"headroom--unpinned",top:"headroom--top",notTop:"headroom--not-top",initial:"headroom"}},e.cutsTheMustard="undefined"!=typeof f&&f.rAF&&f.bind&&f.classList,e}); | jdh8/cdnjs | ajax/libs/headroom/0.7.1/headroom.min.js | JavaScript | mit | 4,565 |
"""The ``lxml.isoschematron`` package implements ISO Schematron support on top
of the pure-xslt 'skeleton' implementation.
"""
import sys
import os.path
from lxml import etree as _etree # due to validator __init__ signature
# some compat stuff, borrowed from lxml.html
try:
bytes
except NameError:
# Python < 2.6
bytes = str
try:
unicode
except NameError:
# Python 3
unicode = str
try:
basestring
except NameError:
# Python 3
basestring = str
__all__ = ['extract_xsd', 'extract_rng', 'iso_dsdl_include',
'iso_abstract_expand', 'iso_svrl_for_xslt1',
'svrl_validation_errors', 'schematron_schema_valid',
'stylesheet_params', 'Schematron']
# some namespaces
#FIXME: Maybe lxml should provide a dedicated place for common namespace
#FIXME: definitions?
XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"
RELAXNG_NS = "http://relaxng.org/ns/structure/1.0"
SCHEMATRON_NS = "http://purl.oclc.org/dsdl/schematron"
SVRL_NS = "http://purl.oclc.org/dsdl/svrl"
# some helpers
_schematron_root = '{%s}schema' % SCHEMATRON_NS
_xml_schema_root = '{%s}schema' % XML_SCHEMA_NS
_resources_dir = os.path.join(os.path.dirname(__file__), 'resources')
# the iso-schematron skeleton implementation steps aka xsl transformations
extract_xsd = _etree.XSLT(_etree.parse(
os.path.join(_resources_dir, 'xsl', 'XSD2Schtrn.xsl')))
extract_rng = _etree.XSLT(_etree.parse(
os.path.join(_resources_dir, 'xsl', 'RNG2Schtrn.xsl')))
iso_dsdl_include = _etree.XSLT(_etree.parse(
os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1',
'iso_dsdl_include.xsl')))
iso_abstract_expand = _etree.XSLT(_etree.parse(
os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1',
'iso_abstract_expand.xsl')))
iso_svrl_for_xslt1 = _etree.XSLT(_etree.parse(
os.path.join(_resources_dir,
'xsl', 'iso-schematron-xslt1', 'iso_svrl_for_xslt1.xsl')))
# svrl result accessors
svrl_validation_errors = _etree.XPath(
'//svrl:failed-assert', namespaces={'svrl': SVRL_NS})
# RelaxNG validator for schematron schemas
schematron_schema_valid = _etree.RelaxNG(_etree.parse(
os.path.join(_resources_dir, 'rng', 'iso-schematron.rng')))
def stylesheet_params(**kwargs):
"""Convert keyword args to a dictionary of stylesheet parameters.
XSL stylesheet parameters must be XPath expressions, i.e.:
* string expressions, like "'5'"
* simple (number) expressions, like "5"
* valid XPath expressions, like "/a/b/text()"
This function converts native Python keyword arguments to stylesheet
parameters following these rules:
If an arg is a string wrap it with XSLT.strparam().
If an arg is an XPath object use its path string.
If arg is None raise TypeError.
Else convert arg to string.
"""
result = {}
for key, val in kwargs.items():
if isinstance(val, basestring):
val = _etree.XSLT.strparam(val)
elif val is None:
raise TypeError('None not allowed as a stylesheet parameter')
elif not isinstance(val, _etree.XPath):
val = unicode(val)
result[key] = val
return result
# helper function for use in Schematron __init__
def _stylesheet_param_dict(paramsDict, kwargsDict):
"""Return a copy of paramsDict, updated with kwargsDict entries, wrapped as
stylesheet arguments.
kwargsDict entries with a value of None are ignored.
"""
# beware of changing mutable default arg
paramsDict = dict(paramsDict)
for k, v in kwargsDict.items():
if v is not None: # None values do not override
paramsDict[k] = v
paramsDict = stylesheet_params(**paramsDict)
return paramsDict
class Schematron(_etree._Validator):
"""An ISO Schematron validator.
Pass a root Element or an ElementTree to turn it into a validator.
Alternatively, pass a filename as keyword argument 'file' to parse from
the file system.
Built on the Schematron language 'reference' skeleton pure-xslt
implementation, the validator is created as an XSLT 1.0 stylesheet using
these steps:
0) (Extract from XML Schema or RelaxNG schema)
1) Process inclusions
2) Process abstract patterns
3) Compile the schematron schema to XSLT
The ``include`` and ``expand`` keyword arguments can be used to switch off
steps 1) and 2).
To set parameters for steps 1), 2) and 3) hand parameter dictionaries to the
keyword arguments ``include_params``, ``expand_params`` or
``compile_params``.
For convenience, the compile-step parameter ``phase`` is also exposed as a
keyword argument ``phase``. This takes precedence if the parameter is also
given in the parameter dictionary.
If ``store_schematron`` is set to True, the (included-and-expanded)
schematron document tree is stored and available through the ``schematron``
property.
If ``store_xslt`` is set to True, the validation XSLT document tree will be
stored and can be retrieved through the ``validator_xslt`` property.
With ``store_report`` set to True (default: False), the resulting validation
report document gets stored and can be accessed as the ``validation_report``
property.
Schematron is a less well known, but very powerful schema language. The main
idea is to use the capabilities of XPath to put restrictions on the structure
and the content of XML documents. Here is a simple example::
>>> from lxml import isoschematron
>>> schematron = isoschematron.Schematron(etree.XML('''
... <schema xmlns="http://purl.oclc.org/dsdl/schematron" >
... <pattern id="id_only_attribute">
... <title>id is the only permitted attribute name</title>
... <rule context="*">
... <report test="@*[not(name()='id')]">Attribute
... <name path="@*[not(name()='id')]"/> is forbidden<name/>
... </report>
... </rule>
... </pattern>
... </schema>
... '''))
>>> xml = etree.XML('''
... <AAA name="aaa">
... <BBB id="bbb"/>
... <CCC color="ccc"/>
... </AAA>
... ''')
>>> schematron.validate(xml)
0
>>> xml = etree.XML('''
... <AAA id="aaa">
... <BBB id="bbb"/>
... <CCC/>
... </AAA>
... ''')
>>> schematron.validate(xml)
1
"""
# libxml2 error categorization for validation errors
_domain = _etree.ErrorDomains.SCHEMATRONV
_level = _etree.ErrorLevels.ERROR
_error_type = _etree.ErrorTypes.SCHEMATRONV_ASSERT
def _extract(self, element):
"""Extract embedded schematron schema from non-schematron host schema.
This method will only be called by __init__ if the given schema document
is not a schematron schema by itself.
Must return a schematron schema document tree or None.
"""
schematron = None
if element.tag == _xml_schema_root:
schematron = self._extract_xsd(element)
elif element.nsmap[element.prefix] == RELAXNG_NS:
# RelaxNG does not have a single unique root element
schematron = self._extract_rng(element)
return schematron
# customization points
# etree.XSLT objects that provide the extract, include, expand, compile
# steps
_extract_xsd = extract_xsd
_extract_rng = extract_rng
_include = iso_dsdl_include
_expand = iso_abstract_expand
_compile = iso_svrl_for_xslt1
# etree.XPath object that determines input document validity when applied to
# the svrl result report; must return a list of result elements (empty if
# valid)
_validation_errors = svrl_validation_errors
def __init__(self, etree=None, file=None, include=True, expand=True,
include_params={}, expand_params={}, compile_params={},
store_schematron=False, store_xslt=False, store_report=False,
phase=None):
super(Schematron, self).__init__()
self._store_report = store_report
self._schematron = None
self._validator_xslt = None
self._validation_report = None
# parse schema document, may be a schematron schema or an XML Schema or
# a RelaxNG schema with embedded schematron rules
try:
if etree is not None:
if isinstance(etree, _etree._Element):
root = etree
else:
root = etree.getroot()
elif file is not None:
root = _etree.parse(file).getroot()
except Exception:
raise _etree.SchematronParseError(
"No tree or file given: %s" % sys.exc_info()[1])
if root is None:
raise ValueError("Empty tree")
if root.tag == _schematron_root:
schematron = root
else:
schematron = self._extract(root)
if schematron is None:
raise _etree.SchematronParseError(
"Document is not a schematron schema or schematron-extractable")
# perform the iso-schematron skeleton implementation steps to get a
# validating xslt
if include:
schematron = self._include(schematron, **include_params)
if expand:
schematron = self._expand(schematron, **expand_params)
if not schematron_schema_valid(schematron):
raise _etree.SchematronParseError(
"invalid schematron schema: %s" %
schematron_schema_valid.error_log)
if store_schematron:
self._schematron = schematron
# add new compile keyword args here if exposing them
compile_kwargs = {'phase': phase}
compile_params = _stylesheet_param_dict(compile_params, compile_kwargs)
validator_xslt = self._compile(schematron, **compile_params)
if store_xslt:
self._validator_xslt = validator_xslt
self._validator = _etree.XSLT(validator_xslt)
def __call__(self, etree):
"""Validate doc using Schematron.
Returns true if document is valid, false if not.
"""
self._clear_error_log()
result = self._validator(etree)
if self._store_report:
self._validation_report = result
errors = self._validation_errors(result)
if errors:
if isinstance(etree, _etree._Element):
fname = etree.getroottree().docinfo.URL or '<file>'
else:
fname = etree.docinfo.URL or '<file>'
for error in errors:
# Does svrl report the line number, anywhere? Don't think so.
self._append_log_message(
domain=self._domain, type=self._error_type,
level=self._level, line=0, message=_etree.tounicode(error),
filename=fname)
return False
return True
def schematron(self):
"""ISO-schematron schema document (None if object has been initialized
with store_schematron=False).
"""
return self._schematron
schematron = property(schematron, doc=schematron.__doc__)
def validator_xslt(self):
"""ISO-schematron skeleton implementation XSLT validator document (None
if object has been initialized with store_xslt=False).
"""
return self._validator_xslt
validator_xslt = property(validator_xslt, doc=validator_xslt.__doc__)
def validation_report(self):
"""ISO-schematron validation result report (None if result-storing has
been turned off).
"""
return self._validation_report
validation_report = property(validation_report, doc=validation_report.__doc__)
| ktan2020/legacy-automation | win/Lib/site-packages/lxml/isoschematron/__init__.py | Python | mit | 11,839 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Globalization;
using System.Net.NetworkInformation;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
namespace System.Net
{
public class WebProxy : IWebProxy, ISerializable
{
private ArrayList _bypassList;
private Regex[] _regExBypassList;
public WebProxy() : this((Uri)null, false, null, null) { }
public WebProxy(Uri Address) : this(Address, false, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal) : this(Address, BypassOnLocal, null, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList) : this(Address, BypassOnLocal, BypassList, null) { }
public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
{
this.Address = Address;
this.Credentials = Credentials;
this.BypassProxyOnLocal = BypassOnLocal;
if (BypassList != null)
{
_bypassList = new ArrayList(BypassList);
UpdateRegExList(true);
}
}
public WebProxy(string Host, int Port)
: this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null)
{
}
public WebProxy(string Address)
: this(CreateProxyUri(Address), false, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal)
: this(CreateProxyUri(Address), BypassOnLocal, null, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, null)
{
}
public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials)
: this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials)
{
}
public Uri Address { get; set; }
public bool BypassProxyOnLocal { get; set; }
public string[] BypassList
{
get { return _bypassList != null ? (string[])_bypassList.ToArray(typeof(string)) : Array.Empty<string>(); }
set
{
_bypassList = new ArrayList(value);
UpdateRegExList(true);
}
}
public ArrayList BypassArrayList => _bypassList ?? (_bypassList = new ArrayList());
public ICredentials Credentials { get; set; }
public bool UseDefaultCredentials
{
get { return Credentials == CredentialCache.DefaultCredentials; }
set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
}
public Uri GetProxy(Uri destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
return IsBypassed(destination) ? destination : Address;
}
private static Uri CreateProxyUri(string address) =>
address == null ? null :
address.IndexOf("://") == -1 ? new Uri("http://" + address) :
new Uri(address);
private void UpdateRegExList(bool canThrow)
{
Regex[] regExBypassList = null;
ArrayList bypassList = _bypassList;
try
{
if (bypassList != null && bypassList.Count > 0)
{
regExBypassList = new Regex[bypassList.Count];
for (int i = 0; i < bypassList.Count; i++)
{
regExBypassList[i] = new Regex((string)bypassList[i], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
}
catch
{
if (!canThrow)
{
_regExBypassList = null;
return;
}
throw;
}
// Update field here, as it could throw earlier in the loop
_regExBypassList = regExBypassList;
}
private bool IsMatchInBypassList(Uri input)
{
UpdateRegExList(false);
if (_regExBypassList != null)
{
string matchUriString = input.IsDefaultPort ?
input.Scheme + "://" + input.Host :
input.Scheme + "://" + input.Host + ":" + input.Port.ToString();
foreach (Regex r in _regExBypassList)
{
if (r.IsMatch(matchUriString))
{
return true;
}
}
}
return false;
}
private bool IsLocal(Uri host)
{
string hostString = host.Host;
IPAddress hostAddress;
if (IPAddress.TryParse(hostString, out hostAddress))
{
return IPAddress.IsLoopback(hostAddress) || IsAddressLocal(hostAddress);
}
// No dot? Local.
int dot = hostString.IndexOf('.');
if (dot == -1)
{
return true;
}
// If it matches the primary domain, it's local. (Whether or not the hostname matches.)
string local = "." + IPGlobalProperties.GetIPGlobalProperties().DomainName;
return
local.Length == (hostString.Length - dot) &&
string.Compare(local, 0, hostString, dot, local.Length, StringComparison.OrdinalIgnoreCase) == 0;
}
private static bool IsAddressLocal(IPAddress ipAddress)
{
// Perf note: The .NET Framework caches this and then uses network change notifications to track
// whether the set should be recomputed. We could consider doing the same if this is observed as
// a bottleneck, but that tracking has its own costs.
IPAddress[] localAddresses = Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList; // TODO: Use synchronous GetHostEntry when available
for (int i = 0; i < localAddresses.Length; i++)
{
if (ipAddress.Equals(localAddresses[i]))
{
return true;
}
}
return false;
}
public bool IsBypassed(Uri host)
{
if (host == null)
{
throw new ArgumentNullException(nameof(host));
}
return
Address == null ||
host.IsLoopback ||
(BypassProxyOnLocal && IsLocal(host)) ||
IsMatchInBypassList(host);
}
protected WebProxy(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
[Obsolete("This method has been deprecated. Please use the proxy selected for you by default. http://go.microsoft.com/fwlink/?linkid=14202")]
public static WebProxy GetDefaultProxy()
{
// The .NET Framework here returns a proxy that fetches IE settings and
// executes JavaScript to determine the correct proxy.
throw new PlatformNotSupportedException();
}
}
}
| mazong1123/corefx | src/System.Net.WebProxy/src/System/Net/WebProxy.cs | C# | mit | 8,037 |
/*! formstone v1.2.2 [upload.js] 2016-09-30 | GPL-3.0 License | formstone.it */
!function(a){"function"==typeof define&&define.amd?define(["jquery","./core"],a):a(jQuery,Formstone)}(function(a,b){"use strict";function c(a){if(b.support.file){var c="";a.label!==!1&&(c+='<div class="'+w.target+'">',c+=a.label,c+="</div>"),c+='<input class="'+w.input+'" type="file"',a.multiple&&(c+=" multiple"),a.accept&&(c+=' accept="'+a.accept+'"'),c+=">",a.baseClasses=[w.base,a.theme,a.customClass].join(" "),this.addClass(a.baseClasses).append(c),a.$input=this.find(v.input),a.queue=[],a.total=0,a.uploading=!1,a.disabled=!0,a.aborting=!1,this.on(x.click,v.target,a,i).on(x.dragEnter,a,m).on(x.dragOver,a,n).on(x.dragLeave,a,o).on(x.drop,a,p),a.$input.on(x.focus,a,j).on(x.blur,a,k).on(x.change,a,l),h.call(this,a)}}function d(a){b.support.file&&(a.$input.off(x.namespace),this.off(x.namespace).removeClass(a.baseClasses).html(""))}function e(b,c){var d;b.aborting=!0;for(var e in b.queue)b.queue.hasOwnProperty(e)&&(d=b.queue[e],("undefined"===a.type(c)||c>=0&&d.index===c)&&(d.started&&!d.complete?d.transfer.abort():f(b,d,"abort")));b.aborting=!1,s(b)}function f(a,b,c){b.error=!0,a.$el.trigger(x.fileError,[b,c]),a.aborting||s(a)}function g(a){a.disabled||(this.addClass(w.disabled),a.$input.prop("disabled",!0),a.disabled=!0)}function h(a){a.disabled&&(this.removeClass(w.disabled),a.$input.prop("disabled",!1),a.disabled=!1)}function i(a){y.killEvent(a);var b=a.data;b.disabled||b.$input.trigger(x.click)}function j(a){a.data.$el.addClass(w.focus)}function k(a){a.data.$el.removeClass(w.focus)}function l(a){y.killEvent(a);var b=a.data,c=b.$input[0].files;!b.disabled&&c.length&&q(b,c)}function m(a){y.killEvent(a);var b=a.data;b.$el.addClass(w.dropping).trigger(x.fileDragEnter)}function n(a){y.killEvent(a);var b=a.data;b.$el.addClass(w.dropping).trigger(x.fileDragOver)}function o(a){y.killEvent(a);var b=a.data;b.$el.removeClass(w.dropping).trigger(x.fileDragLeave)}function p(a){y.killEvent(a);var b=a.data,c=a.originalEvent.dataTransfer.files;b.$el.removeClass(w.dropping),b.disabled||q(b,c)}function q(a,b){for(var c=[],d=0;d<b.length;d++){var e={index:a.total++,file:b[d],name:b[d].name,size:b[d].size,started:!1,complete:!1,error:!1,transfer:null};c.push(e),a.queue.push(e)}a.$el.trigger(x.queued,[c]),a.autoUpload&&r(a),a.$input.val("")}function r(a){a.uploading||(z.on(x.beforeUnload,function(){return a.leave}),a.uploading=!0,a.$el.trigger(x.start,[a.queue])),s(a)}function s(a){var b=0,c=[];for(var d in a.queue)!a.queue.hasOwnProperty(d)||a.queue[d].complete||a.queue[d].error||c.push(a.queue[d]);a.queue=c;for(var e in a.queue)if(a.queue.hasOwnProperty(e)){if(!a.queue[e].started){var f=new FormData;f.append(a.postKey,a.queue[e].file);for(var g in a.postData)a.postData.hasOwnProperty(g)&&f.append(g,a.postData[g]);t(a,f,a.queue[e])}if(b++,b>=a.maxQueue)return;d++}0===b&&(z.off(x.beforeUnload),a.uploading=!1,a.$el.trigger(x.complete))}function t(b,c,d){c=b.beforeSend.call(b.$el,c,d),d.size>=b.maxSize||c===!1||d.error===!0?f(b,d,c?"size":"abort"):(d.started=!0,d.transfer=a.ajax({url:b.action,data:c,dataType:b.dataType,type:"POST",contentType:!1,processData:!1,cache:!1,xhr:function(){var c=a.ajaxSettings.xhr();return c.upload&&c.upload.addEventListener("progress",function(a){var c=0,e=a.loaded||a.position,f=a.total;a.lengthComputable&&(c=Math.ceil(e/f*100)),b.$el.trigger(x.fileProgress,[d,c])},!1),c},beforeSend:function(a,c){b.$el.trigger(x.fileStart,[d])},success:function(a,c,e){d.complete=!0,b.$el.trigger(x.fileComplete,[d,a]),s(b)},error:function(a,c,e){f(b,d,e)}}))}var u=b.Plugin("upload",{widget:!0,defaults:{accept:!1,action:"",autoUpload:!0,beforeSend:function(a){return a},customClass:"",dataType:"html",label:"Drag and drop files or click to select",leave:"You have uploads pending, are you sure you want to leave this page?",maxQueue:2,maxSize:5242880,multiple:!0,postData:{},postKey:"file",theme:"fs-light"},classes:["input","target","multiple","dropping","disabled","focus"],methods:{_construct:c,_destruct:d,disable:g,enable:h,abort:e,start:r}}),v=u.classes,w=v.raw,x=u.events,y=u.functions,z=(b.window,b.$window);x.complete="complete",x.fileComplete="filecomplete",x.fileDragEnter="filedragenter",x.fileDragLeave="filedragleave",x.fileDragOver="filedragover",x.fileError="fileerror",x.fileProgress="fileprogress",x.fileStart="filestart",x.start="start",x.queued="queued"}); | him2him2/cdnjs | ajax/libs/formstone/1.2.2/js/upload.js | JavaScript | mit | 4,412 |
module.exports={title:"Babel",slug:"babel",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Babel</title><path d="M15.76 0c-1.603.147-3.719.713-6.317 1.719a22.366 22.366 0 01-2.44 1.539l.01.158c.064 0 .136-.043.24-.096.106-.01.169.032.169.137l.168-.094.084-.011.01.074c.01.073-.566.523-1.707 1.33l.093.146-.084.012-.177-.064c0 .052-.073.085-.24.095l.01.084.189.21a.673.673 0 01-.252-.053c-.367.031-.734.303-1.09.806l.094.147c.314-.283.492-.43.544-.43l.022.23c-.052 0-.136.042-.24.094l.199.295A5.86 5.86 0 016.29 5.291c.23.063.346.125.346.209l.168-.01c1.225-.911 2.44-1.562 3.644-1.97l.012.158c-.22.335-.377.501-.461.511.01.116.052.21.115.305.021.21-.524 1.583-1.635 4.139-2.535 5.93-4.651 10.307-6.359 13.156 0 .052.041.136.094.23.419-.104.691-.197.806-.302l.096-.012.01.158.158-.011.166-.094c0 .052.063.073.168.062l.012.159c.01.157-.075.397-.274.722-.178.2-.355.607-.554 1.225l.01.074.158-.01c.68-.764 1.204-1.52 1.56-2.254 2.001-.586 3.52-1.162 4.578-1.728 1.058-.094 1.876-.365 2.42-.826l-.011-.084-.399.115-.094.01-.01-.084c.776-.116 1.32-.293 1.614-.524 1.519-1.173 2.66-2 3.435-2.492 2.4-1.76 3.531-3.457 3.395-5.07-.01-.168-.545-.828-1.582-1.98-.021-.22.345-.535 1.078-.954l2.086-1.834c.46-.597.744-1.56.838-2.89l-.031-.315c-.084-.932-.756-1.687-2.034-2.264C19.06.303 17.708.031 15.76 0zm2.525 1.037c1.55.063 2.347.335 2.389.817l-.063.158-2.326-.975zm-1.482 1.317c1.063-.016 1.617.267 1.672.863l.156-.012-.031-.398.168-.01c.408.22.627.492.648.816.021.22-.094.494-.355.819-.105.01-.168-.064-.178-.221l-.168.012-.041.47c-.702 1.048-1.205 1.582-1.52 1.614-.283.387-.462.587-.535.597-.22.262-.816.712-1.8 1.34-.325.032-1.531.493-3.616 1.404a.595.595 0 00-.334-.052l-.012-.147c-.02-.304.107-.681.41-1.142.158-.86.335-1.352.534-1.467l1.738-3.906c-.02-.241.347-.43 1.111-.555l.252-.022.02.221a50.387 50.387 0 011.394-.2c.173-.014.335-.022.487-.024zm3.619.39h.027c.139.012.288.263.446.744l.01.147c-.085.01-.24-.242-.471-.744l-.012-.147zm-9.836 2.483h.072l.022.23c-.074.01-.177.116-.303.336l-.012-.156c.147-.178.22-.316.22-.41zM5.6 5.354l.01.072c-.053 0-.136.043-.24.095l-.085.01-.01-.146.325-.031zM9.885 6.86l.031.315-.084.01-.031-.313.084-.012zm-.2.567c-.02.262-.084.397-.22.408l-.084.01c.094-.178.147-.303.137-.397l.168-.021zm-.345.816l.01.074-.147.25-.158.012-.01-.074c.157-.01.231-.093.22-.25l.085-.012zm-.358.735l-.04.386-.085.01-.03-.387.155-.01zm8.497.28l.345.212c.01.104-.042.167-.146.177-.147-.094-.262-.136-.346-.136l-.021-.23.168-.022zm-6.653.891l.012.147-.326.033-.01-.148.324-.032zm5.363.545c.23.105.347.21.358.293l.01.075c-.22.02-.42-.095-.608-.346l.24-.022zm2.6.252c.178.074.261.148.272.221l.052.617c-.073.168-.146.252-.23.252l-.094-1.09zm-4.195.065c.84-.014 1.482.184 1.922.605l.03.315c-.376 1.09-.795 1.719-1.245 1.918l-2.096 1.666c-1.56 1.026-2.4 1.538-2.525 1.548-2.483 1.373-4.032 2.075-4.63 2.127l-.095.01c.084-.293 1.185-2.555 3.322-6.808.943-.084 2.43-.525 4.452-1.32l.492-.042c.128-.01.253-.017.373-.02zm-3.055.49l.01.074-.334.031-.012-.074.336-.031zm-5.226 5.07c-.105.535-.221.808-.336.819l-.01-.075c-.021-.272.094-.513.346-.744zm7.101.336l.01.147c.01.063-.23.261-.701.607-1.394.681-2.21 1.152-2.452 1.393-1.508.523-2.252.849-2.242.974-1.34.535-2.22.923-2.638 1.164-.095.01-.241-.031-.43-.115-.021-.272.093-.494.365-.672.23-.02.463.011.672.106.251-.126.68-.274 1.299-.42l-.012-.156-.492.04c.063-.083.535-.303 1.436-.67l.251-.02.01.073c-.419.032-.66.167-.713.387.01.094.064.147.168.137.304-.21.461-.324.461-.356.608-.115 2.274-.995 5.008-2.619zm-7.584.723l.01.072c.01.105-.042.17-.147.18l-.01-.074c-.01-.095.042-.157.147-.178zm3.77.937c.089-.002.139.049.148.131-.199.021-.566.178-1.121.492l-.084.01-.01-.156a1.586 1.586 0 001.026-.47c.014-.003.028-.006.04-.007zm-3.664 1.243l.01.082c-.064 0-.138.043-.243.095l-.156.01c-.01-.073.032-.136.137-.168l.252-.02zm-1.918.953l.177.072c-.063.471-.198.713-.44.734a1.076 1.076 0 00-.513-.105l-.021-.23c-.01-.095.043-.147.158-.178.105-.01.167.061.178.218.282-.345.44-.511.46-.511Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://github.com/babel/website/blob/93330158b6ecca1ab88d3be8dbf661f5c2da6c76/website/static/img/babel-black.svg",hex:"F9DC3E",guidelines:void 0,license:void 0}; | cdnjs/cdnjs | ajax/libs/simple-icons/5.6.0/babel.js | JavaScript | mit | 4,214 |
L.Control.Permalink=L.Control.extend({includes:L.Mixin.Events,options:{position:"bottomleft",useAnchor:!0,useLocation:!1,text:"Permalink"},initialize:function(t){L.Util.setOptions(this,t),this._params={},this._set_urlvars(),this.on("update",this._set_center,this);for(var i in this)"string"==typeof i&&0===i.indexOf("initialize_")&&this[i]()},onAdd:function(t){if(this._container=L.DomUtil.create("div","leaflet-control-attribution leaflet-control-permalink"),L.DomEvent.disableClickPropagation(this._container),this._map=t,this._href=L.DomUtil.create("a",null,this._container),this._href.innerHTML=this.options.text,t.on("moveend",this._update_center,this),this.fire("update",{params:this._params}),this._update_center(),this.options.useAnchor&&"onhashchange"in window){var i=this,r=window.onhashchange;window.onhashchange=function(){return i._set_urlvars(),r?r():void 0}}return this.fire("add",{map:t}),this._container},_update_center:function(){if(this._map){var t=this._round_point(this._map.getCenter());this._update({zoom:String(this._map.getZoom()),lat:String(t.lat),lon:String(t.lng)})}},_update_href:function(){var t=L.Util.getParamString(this._params),i="?";this.options.useAnchor&&(i="#");var r=this._url_base+i+t.slice(1);return this._href&&this._href.setAttribute("href",r),this.options.useLocation&&location.replace("#"+t.slice(1)),r},_round_point:function(t){var i=this._map.getBounds(),r=this._map.getSize(),n=i.getNorthEast(),e=i.getSouthWest(),a=function(t,i){if(0===i)return t;for(var r=1;1>i&&i>-1;)t*=10,i*=10,r*=10;return Math.floor(t)/r};return t.lat=a(t.lat,(n.lat-e.lat)/r.y),t.lng=a(t.lng,(n.lng-e.lng)/r.x),t},_update:function(t,i){for(var r in t)t.hasOwnProperty(r)&&(null!==t[r]&&void 0!==t[r]?this._params[r]=t[r]:delete this._params[r]);this._update_href()},_set_urlvars:function(){function t(t,i){for(var r in t)if(t.hasOwnProperty(r)&&t[r]!==i[r])return!1;return!0}this._url_base=window.location.href.split("#")[0].split("?")[0];var i;i=this.options.useAnchor?L.UrlUtil.queryParse(L.UrlUtil.hash()):L.UrlUtil.queryParse(L.UrlUtil.query()),t(i,this._params)&&t(this._params,i)||(this._params=i,this._update_href(),this.fire("update",{params:this._params}))},_set_center:function(t){var i=t.params;void 0!==i.zoom&&void 0!==i.lat&&void 0!==i.lon&&this._map.setView(new L.LatLng(i.lat,i.lon),i.zoom)}}),L.UrlUtil={queryParse:function(t){var i={},r="&";-1!==t.search("&")&&(r="&");for(var n=t.split(r),e=0;e<n.length;e++){var a=n[e].split("=");2===a.length&&(i[a[0]]=decodeURI(a[1]))}return i},query:function(){var t=window.location.href.split("#")[0],i=t.indexOf("?");return 0>i?"":t.slice(i+1)},hash:function(){return window.location.hash.slice(1)},updateParamString:function(t,i){var r=L.UrlUtil.queryParse(t);for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n]);return L.Util.getParamString(r).slice(1)}};
//# sourceMappingURL=./1.3.9/control/Permalink.min.js.map | nolsherry/cdnjs | ajax/libs/leaflet-plugins/1.3.9/control/Permalink.min.js | JavaScript | mit | 2,899 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/cldr/nls/hu/islamic",{"months-format-narrow":["1","2","3","4","5","6","7","8","9","10","11","12"],"months-format-wide":["Moharrem","Safar","Rébi el avvel","Rébi el accher","Dsemádi el avvel","Dsemádi el accher","Redseb","Sabán","Ramadán","Sevvál","Dsül kade","Dsül hedse"],"months-standAlone-abbr":["Muh.","Saf.","Rab. I","Rab. II","Jum. I","Jum. II","Raj.","Sha.","Ram.","Shaw.","Dsül-Q.","Dsül-H."],"months-standAlone-wide":["Moharrem","Safar","Rébi I","Rébi II","Dsemádi I","Dsemádi II","Redseb","Sabán","Ramadán","Sevvál","Dsül kade","Dsül hedse"],"eraAbbr":["MF"],"dateFormat-full":"y. MMMM d., EEEE","dateFormat-long":"y. MMMM d.","dateFormat-medium":"yyyy.MM.dd.","dateFormat-short":"yyyy.MM.dd.","dateFormatItem-d":"d","dateFormatItem-Ed":"d E","dateFormatItem-h":"a h","dateFormatItem-H":"HH","dateFormatItem-hm":"a h:mm","dateFormatItem-Hm":"H:mm","dateFormatItem-hms":"a h:mm:ss","dateFormatItem-Hms":"H:mm:ss","dateFormatItem-M":"L","dateFormatItem-Md":"M. d.","dateFormatItem-MEd":"M. d., E","dateFormatItem-MMMd":"MMM d.","dateFormatItem-MMMEd":"MMM. d., E","dateFormatItem-MMMMd":"MMMM d.","dateFormatItem-ms":"mm:ss","dateFormatItem-y":"y","dateFormatItem-yM":"y-M","dateFormatItem-yMEd":"yyyy.MM.dd., E","dateFormatItem-yMMM":"y MMM","dateFormatItem-yMMMEd":"y. MMM d., E","dateFormatItem-yQ":"y Q","dateFormatItem-yQQQ":"y QQQ","months-format-abbr":["Moharrem","Safar","Rébi el avvel","Rébi el accher","Dsemádi el avvel","Dsemádi el accher","Redseb","Sabán","Ramadán","Sevvál","Dsül kade","Dsül hedse"],"eraNames":["MF"],"eraNarrow":["MF"],"days-format-abbr":["V","H","K","Sze","Cs","P","Szo"],"days-format-narrow":["V","H","K","Sz","Cs","P","Sz"],"days-format-wide":["vasárnap","hétfő","kedd","szerda","csütörtök","péntek","szombat"],"days-standAlone-abbr":["V","H","K","Sze","Cs","P","Szo"],"days-standAlone-narrow":["V","H","K","Sz","Cs","P","Sz"],"days-standAlone-wide":["vasárnap","hétfő","kedd","szerda","csütörtök","péntek","szombat"],"quarters-format-abbr":["N1","N2","N3","N4"],"quarters-format-wide":["I. negyedév","II. negyedév","III. negyedév","IV. negyedév"],"quarters-standAlone-abbr":["N1","N2","N3","N4"],"quarters-standAlone-wide":["1. negyedév","2. negyedév","3. negyedév","4. negyedév"],"dayPeriods-format-narrow-am":"de.","dayPeriods-format-narrow-pm":"du.","dayPeriods-format-wide-am":"de.","dayPeriods-format-wide-pm":"du.","dateFormatItem-yMd":"yyyy.MM.dd.","dateFormatItem-yMMMd":"y. MMM d.","timeFormat-full":"H:mm:ss zzzz","timeFormat-long":"H:mm:ss z","timeFormat-medium":"H:mm:ss","timeFormat-short":"H:mm"});
| danut007ro/cdnjs | ajax/libs/dojo/1.8.0/cldr/nls/hu/islamic.js | JavaScript | mit | 2,826 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/cldr/nls/pt/hebrew",{"months-format-abbr":["Tishri","Heshvan","Kislev","Tevet","Shevat","Adar I","Adar","Nisan","Iyar","Sivan","Tamuz","Av","Elul"],"months-format-abbr-leap":"Adar II","months-format-wide":["Tishri","Heshvan","Kislev","Tevet","Shevat","Adar I","Adar","Nisan","Iyar","Sivan","Tamuz","Av","Elul"],"months-format-wide-leap":"Adar II","months-standAlone-abbr":["Tishri","Heshvan","Kislev","Tevet","Shevat","Adar I","Adar","Nisan","Iyar","Sivan","Tamuz","Av","Elul"],"months-standAlone-abbr-leap":"Adar II","months-standAlone-wide":["Tishri","Heshvan","Kislev","Tevet","Shevat","Adar I","Adar","Nisan","Iyar","Sivan","Tamuz","Av","Elul"],"months-standAlone-wide-leap":"Adar II","days-format-abbr":["dom","seg","ter","qua","qui","sex","sáb"],"days-format-wide":["domingo","segunda-feira","terça-feira","quarta-feira","quinta-feira","sexta-feira","sábado"],"days-standAlone-narrow":["D","S","T","Q","Q","S","S"],"quarters-format-abbr":["T1","T2","T3","T4"],"quarters-format-wide":["1º trimestre","2º trimestre","3º trimestre","4º trimestre"],"quarters-standAlone-wide":["1º trimestre","2º trimestre","3º trimestre","4º trimestre"],"dayPeriods-format-narrow-am":"a","dayPeriods-format-narrow-pm":"p","dateFormat-full":"EEEE, d 'de' MMMM 'de' y","dateFormat-long":"d 'de' MMMM 'de' y","dateFormat-medium":"dd/MM/yyyy","dateFormat-short":"dd/MM/yy","dateFormatItem-Ed":"E, d","dateFormatItem-Hm":"HH'h'mm","dateFormatItem-Md":"d/M","dateFormatItem-MEd":"E, dd/MM","dateFormatItem-MMMd":"d 'de' MMM","dateFormatItem-MMMEd":"E, d 'de' MMM","dateFormatItem-ms":"mm'min'ss's'","dateFormatItem-yM":"MM/yyyy","dateFormatItem-yMd":"dd/MM/yyyy","dateFormatItem-yMEd":"E, dd/MM/yyyy","dateFormatItem-yMMM":"MMM 'de' y","dateFormatItem-yMMMd":"d 'de' MMM 'de' y","dateFormatItem-yMMMEd":"E, d 'de' MMM 'de' y","dateFormatItem-yQ":"yyyy Q","timeFormat-full":"HH'h'mm'min'ss's' zzzz","timeFormat-long":"HH'h'mm'min'ss's' z"});
| shallaa/cdnjs | ajax/libs/dojo/1.8.0/cldr/nls/pt/hebrew.js | JavaScript | mit | 2,151 |
(function(global) {
var define = global.define;
var require = global.require;
var Ember = global.Ember;
if (typeof Ember === 'undefined' && typeof require !== 'undefined') {
Ember = require('ember');
}
Ember.libraries.register('Ember Simple Auth Testing', '0.6.4');
define("simple-auth-testing/authenticators/test",
["simple-auth/authenticators/base","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Base = __dependency1__["default"];
__exports__["default"] = Base.extend({
restore: function(data) {
return new Ember.RSVP.resolve();
},
authenticate: function(options) {
return new Ember.RSVP.resolve();
},
invalidate: function(data) {
return new Ember.RSVP.resolve();
}
});
});
define("simple-auth-testing/ember",
["./initializer"],
function(__dependency1__) {
"use strict";
var initializer = __dependency1__["default"];
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer(initializer);
});
});
define("simple-auth-testing/initializer",
["simple-auth-testing/authenticators/test","exports"],
function(__dependency1__, __exports__) {
"use strict";
var TestAuthenticator = __dependency1__["default"];
__exports__["default"] = {
name: 'simple-auth-testing',
before: 'simple-auth',
initialize: function(container, application) {
container.register('simple-auth-authenticator:test', TestAuthenticator);
}
};
});
define("simple-auth-testing/test-helpers",
["simple-auth/configuration","exports"],
function(__dependency1__, __exports__) {
"use strict";
var Configuration = __dependency1__["default"];
var testHelpers = function() {
Ember.Test.registerAsyncHelper('authenticateSession', function(app) {
var session = app.__container__.lookup(Configuration.session);
session.authenticate('simple-auth-authenticator:test');
return wait();
});
Ember.Test.registerAsyncHelper('invalidateSession', function(app) {
var session = app.__container__.lookup(Configuration.session);
if (session.get('isAuthenticated')) {
session.invalidate();
}
return wait();
});
}();
__exports__["default"] = testHelpers;
});
})((typeof global !== 'undefined') ? global : window);
| honestree/cdnjs | ajax/libs/ember-simple-auth/0.6.4/simple-auth-testing.amd.js | JavaScript | mit | 2,417 |
.yasgui{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857;color:#333;background-color:#fff;/*! normalize.css v3.0.2 | MIT License | git.io/normalize *//*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@font-face { font-family:'Glyphicons Halflings';src:url(../fonts/bootstrap/glyphicons-halflings-regular.eot);src:url(../fonts/bootstrap/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/bootstrap/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/bootstrap/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/bootstrap/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-viewport{width:device-width}.yasgui html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}.yasgui body{margin:0}.yasgui article,.yasgui aside,.yasgui details,.yasgui figcaption,.yasgui figure,.yasgui footer,.yasgui header,.yasgui hgroup,.yasgui main,.yasgui menu,.yasgui nav,.yasgui section,.yasgui summary{display:block}.yasgui audio,.yasgui canvas,.yasgui progress,.yasgui video{display:inline-block;vertical-align:baseline}.yasgui audio:not([controls]){display:none;height:0}.yasgui [hidden],.yasgui template{display:none}.yasgui a{background-color:transparent}.yasgui a:active,.yasgui a:hover{outline:0}.yasgui b,.yasgui strong{font-weight:700}.yasgui dfn{font-style:italic}.yasgui h1{margin:.67em 0}.yasgui mark{background:#ff0;color:#000}.yasgui sub,.yasgui sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}.yasgui sup{top:-.5em}.yasgui sub{bottom:-.25em}.yasgui img{border:0}.yasgui svg:not(:root){overflow:hidden}.yasgui hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}.yasgui pre{overflow:auto}.yasgui code,.yasgui kbd,.yasgui pre,.yasgui samp{font-size:1em}.yasgui button,.yasgui input,.yasgui optgroup,.yasgui select,.yasgui textarea{color:inherit;font:inherit;margin:0}.yasgui button{overflow:visible}.yasgui button,.yasgui select{text-transform:none}.yasgui button,.yasgui html input[type=button],.yasgui input[type=reset],.yasgui input[type=submit]{-webkit-appearance:button;cursor:pointer}.yasgui button[disabled],.yasgui html input[disabled]{cursor:default}.yasgui button::-moz-focus-inner,.yasgui input::-moz-focus-inner{border:0;padding:0}.yasgui input[type=radio],.yasgui input[type=checkbox]{box-sizing:border-box;padding:0}.yasgui input[type=number]::-webkit-inner-spin-button,.yasgui input[type=number]::-webkit-outer-spin-button{height:auto}.yasgui input[type=search]::-webkit-search-cancel-button,.yasgui input[type=search]::-webkit-search-decoration{-webkit-appearance:none}.yasgui textarea{overflow:auto}.yasgui optgroup{font-weight:700}.yasgui table{border-collapse:collapse;border-spacing:0}.yasgui td,.yasgui th{padding:0}@media print{.yasgui *,.yasgui :after,.yasgui :before{background:0 0!important;color:#000!important;box-shadow:none!important;text-shadow:none!important}.yasgui a,.yasgui a:visited{text-decoration:underline}.yasgui a[href]:after{content:" (" attr(href) ")"}.yasgui abbr[title]:after{content:" (" attr(title) ")"}.yasgui a[href^="#"]:after,.yasgui a[href^="javascript:"]:after{content:""}.yasgui blockquote,.yasgui pre{border:1px solid #999;page-break-inside:avoid}.yasgui thead{display:table-header-group}.yasgui img,.yasgui tr{page-break-inside:avoid}.yasgui img{max-width:100%!important}.yasgui h2,.yasgui h3,.yasgui p{orphans:3;widows:3}.yasgui h2,.yasgui h3{page-break-after:avoid}.yasgui select{background:#fff!important}.yasgui .navbar{display:none}.yasgui .btn>.caret,.yasgui .dropup>.btn>.caret{border-top-color:#000!important}.yasgui .label{border:1px solid #000}.yasgui .table{border-collapse:collapse!important}.yasgui .table td,.yasgui .table th{background-color:#fff!important}.yasgui .table-bordered td,.yasgui .table-bordered th{border:1px solid #ddd!important}}.yasgui .glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.yasgui .glyphicon-asterisk:before{content:"\2a"}.yasgui .glyphicon-plus:before{content:"\2b"}.yasgui .glyphicon-eur:before,.yasgui .glyphicon-euro:before{content:"\20ac"}.yasgui .glyphicon-minus:before{content:"\2212"}.yasgui .glyphicon-cloud:before{content:"\2601"}.yasgui .glyphicon-envelope:before{content:"\2709"}.yasgui .glyphicon-pencil:before{content:"\270f"}.yasgui .glyphicon-glass:before{content:"\e001"}.yasgui .glyphicon-music:before{content:"\e002"}.yasgui .glyphicon-search:before{content:"\e003"}.yasgui .glyphicon-heart:before{content:"\e005"}.yasgui .glyphicon-star:before{content:"\e006"}.yasgui .glyphicon-star-empty:before{content:"\e007"}.yasgui .glyphicon-user:before{content:"\e008"}.yasgui .glyphicon-film:before{content:"\e009"}.yasgui .glyphicon-th-large:before{content:"\e010"}.yasgui .glyphicon-th:before{content:"\e011"}.yasgui .glyphicon-th-list:before{content:"\e012"}.yasgui .glyphicon-ok:before{content:"\e013"}.yasgui .glyphicon-remove:before{content:"\e014"}.yasgui .glyphicon-zoom-in:before{content:"\e015"}.yasgui .glyphicon-zoom-out:before{content:"\e016"}.yasgui .glyphicon-off:before{content:"\e017"}.yasgui .glyphicon-signal:before{content:"\e018"}.yasgui .glyphicon-cog:before{content:"\e019"}.yasgui .glyphicon-trash:before{content:"\e020"}.yasgui .glyphicon-home:before{content:"\e021"}.yasgui .glyphicon-file:before{content:"\e022"}.yasgui .glyphicon-time:before{content:"\e023"}.yasgui .glyphicon-road:before{content:"\e024"}.yasgui .glyphicon-download-alt:before{content:"\e025"}.yasgui .glyphicon-download:before{content:"\e026"}.yasgui .glyphicon-upload:before{content:"\e027"}.yasgui .glyphicon-inbox:before{content:"\e028"}.yasgui .glyphicon-play-circle:before{content:"\e029"}.yasgui .glyphicon-repeat:before{content:"\e030"}.yasgui .glyphicon-refresh:before{content:"\e031"}.yasgui .glyphicon-list-alt:before{content:"\e032"}.yasgui .glyphicon-lock:before{content:"\e033"}.yasgui .glyphicon-flag:before{content:"\e034"}.yasgui .glyphicon-headphones:before{content:"\e035"}.yasgui .glyphicon-volume-off:before{content:"\e036"}.yasgui .glyphicon-volume-down:before{content:"\e037"}.yasgui .glyphicon-volume-up:before{content:"\e038"}.yasgui .glyphicon-qrcode:before{content:"\e039"}.yasgui .glyphicon-barcode:before{content:"\e040"}.yasgui .glyphicon-tag:before{content:"\e041"}.yasgui .glyphicon-tags:before{content:"\e042"}.yasgui .glyphicon-book:before{content:"\e043"}.yasgui .glyphicon-bookmark:before{content:"\e044"}.yasgui .glyphicon-print:before{content:"\e045"}.yasgui .glyphicon-camera:before{content:"\e046"}.yasgui .glyphicon-font:before{content:"\e047"}.yasgui .glyphicon-bold:before{content:"\e048"}.yasgui .glyphicon-italic:before{content:"\e049"}.yasgui .glyphicon-text-height:before{content:"\e050"}.yasgui .glyphicon-text-width:before{content:"\e051"}.yasgui .glyphicon-align-left:before{content:"\e052"}.yasgui .glyphicon-align-center:before{content:"\e053"}.yasgui .glyphicon-align-right:before{content:"\e054"}.yasgui .glyphicon-align-justify:before{content:"\e055"}.yasgui .glyphicon-list:before{content:"\e056"}.yasgui .glyphicon-indent-left:before{content:"\e057"}.yasgui .glyphicon-indent-right:before{content:"\e058"}.yasgui .glyphicon-facetime-video:before{content:"\e059"}.yasgui .glyphicon-picture:before{content:"\e060"}.yasgui .glyphicon-map-marker:before{content:"\e062"}.yasgui .glyphicon-adjust:before{content:"\e063"}.yasgui .glyphicon-tint:before{content:"\e064"}.yasgui .glyphicon-edit:before{content:"\e065"}.yasgui .glyphicon-share:before{content:"\e066"}.yasgui .glyphicon-check:before{content:"\e067"}.yasgui .glyphicon-move:before{content:"\e068"}.yasgui .glyphicon-step-backward:before{content:"\e069"}.yasgui .glyphicon-fast-backward:before{content:"\e070"}.yasgui .glyphicon-backward:before{content:"\e071"}.yasgui .glyphicon-play:before{content:"\e072"}.yasgui .glyphicon-pause:before{content:"\e073"}.yasgui .glyphicon-stop:before{content:"\e074"}.yasgui .glyphicon-forward:before{content:"\e075"}.yasgui .glyphicon-fast-forward:before{content:"\e076"}.yasgui .glyphicon-step-forward:before{content:"\e077"}.yasgui .glyphicon-eject:before{content:"\e078"}.yasgui .glyphicon-chevron-left:before{content:"\e079"}.yasgui .glyphicon-chevron-right:before{content:"\e080"}.yasgui .glyphicon-plus-sign:before{content:"\e081"}.yasgui .glyphicon-minus-sign:before{content:"\e082"}.yasgui .glyphicon-remove-sign:before{content:"\e083"}.yasgui .glyphicon-ok-sign:before{content:"\e084"}.yasgui .glyphicon-question-sign:before{content:"\e085"}.yasgui .glyphicon-info-sign:before{content:"\e086"}.yasgui .glyphicon-screenshot:before{content:"\e087"}.yasgui .glyphicon-remove-circle:before{content:"\e088"}.yasgui .glyphicon-ok-circle:before{content:"\e089"}.yasgui .glyphicon-ban-circle:before{content:"\e090"}.yasgui .glyphicon-arrow-left:before{content:"\e091"}.yasgui .glyphicon-arrow-right:before{content:"\e092"}.yasgui .glyphicon-arrow-up:before{content:"\e093"}.yasgui .glyphicon-arrow-down:before{content:"\e094"}.yasgui .glyphicon-share-alt:before{content:"\e095"}.yasgui .glyphicon-resize-full:before{content:"\e096"}.yasgui .glyphicon-resize-small:before{content:"\e097"}.yasgui .glyphicon-exclamation-sign:before{content:"\e101"}.yasgui .glyphicon-gift:before{content:"\e102"}.yasgui .glyphicon-leaf:before{content:"\e103"}.yasgui .glyphicon-fire:before{content:"\e104"}.yasgui .glyphicon-eye-open:before{content:"\e105"}.yasgui .glyphicon-eye-close:before{content:"\e106"}.yasgui .glyphicon-warning-sign:before{content:"\e107"}.yasgui .glyphicon-plane:before{content:"\e108"}.yasgui .glyphicon-calendar:before{content:"\e109"}.yasgui .glyphicon-random:before{content:"\e110"}.yasgui .glyphicon-comment:before{content:"\e111"}.yasgui .glyphicon-magnet:before{content:"\e112"}.yasgui .glyphicon-chevron-up:before{content:"\e113"}.yasgui .glyphicon-chevron-down:before{content:"\e114"}.yasgui .glyphicon-retweet:before{content:"\e115"}.yasgui .glyphicon-shopping-cart:before{content:"\e116"}.yasgui .glyphicon-folder-close:before{content:"\e117"}.yasgui .glyphicon-folder-open:before{content:"\e118"}.yasgui .glyphicon-resize-vertical:before{content:"\e119"}.yasgui .glyphicon-resize-horizontal:before{content:"\e120"}.yasgui .glyphicon-hdd:before{content:"\e121"}.yasgui .glyphicon-bullhorn:before{content:"\e122"}.yasgui .glyphicon-bell:before{content:"\e123"}.yasgui .glyphicon-certificate:before{content:"\e124"}.yasgui .glyphicon-thumbs-up:before{content:"\e125"}.yasgui .glyphicon-thumbs-down:before{content:"\e126"}.yasgui .glyphicon-hand-right:before{content:"\e127"}.yasgui .glyphicon-hand-left:before{content:"\e128"}.yasgui .glyphicon-hand-up:before{content:"\e129"}.yasgui .glyphicon-hand-down:before{content:"\e130"}.yasgui .glyphicon-circle-arrow-right:before{content:"\e131"}.yasgui .glyphicon-circle-arrow-left:before{content:"\e132"}.yasgui .glyphicon-circle-arrow-up:before{content:"\e133"}.yasgui .glyphicon-circle-arrow-down:before{content:"\e134"}.yasgui .glyphicon-globe:before{content:"\e135"}.yasgui .glyphicon-wrench:before{content:"\e136"}.yasgui .glyphicon-tasks:before{content:"\e137"}.yasgui .glyphicon-filter:before{content:"\e138"}.yasgui .glyphicon-briefcase:before{content:"\e139"}.yasgui .glyphicon-fullscreen:before{content:"\e140"}.yasgui .glyphicon-dashboard:before{content:"\e141"}.yasgui .glyphicon-paperclip:before{content:"\e142"}.yasgui .glyphicon-heart-empty:before{content:"\e143"}.yasgui .glyphicon-link:before{content:"\e144"}.yasgui .glyphicon-phone:before{content:"\e145"}.yasgui .glyphicon-pushpin:before{content:"\e146"}.yasgui .glyphicon-usd:before{content:"\e148"}.yasgui .glyphicon-gbp:before{content:"\e149"}.yasgui .glyphicon-sort:before{content:"\e150"}.yasgui .glyphicon-sort-by-alphabet:before{content:"\e151"}.yasgui .glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.yasgui .glyphicon-sort-by-order:before{content:"\e153"}.yasgui .glyphicon-sort-by-order-alt:before{content:"\e154"}.yasgui .glyphicon-sort-by-attributes:before{content:"\e155"}.yasgui .glyphicon-sort-by-attributes-alt:before{content:"\e156"}.yasgui .glyphicon-unchecked:before{content:"\e157"}.yasgui .glyphicon-expand:before{content:"\e158"}.yasgui .glyphicon-collapse-down:before{content:"\e159"}.yasgui .glyphicon-collapse-up:before{content:"\e160"}.yasgui .glyphicon-log-in:before{content:"\e161"}.yasgui .glyphicon-flash:before{content:"\e162"}.yasgui .glyphicon-log-out:before{content:"\e163"}.yasgui .glyphicon-new-window:before{content:"\e164"}.yasgui .glyphicon-record:before{content:"\e165"}.yasgui .glyphicon-save:before{content:"\e166"}.yasgui .glyphicon-open:before{content:"\e167"}.yasgui .glyphicon-saved:before{content:"\e168"}.yasgui .glyphicon-import:before{content:"\e169"}.yasgui .glyphicon-export:before{content:"\e170"}.yasgui .glyphicon-send:before{content:"\e171"}.yasgui .glyphicon-floppy-disk:before{content:"\e172"}.yasgui .glyphicon-floppy-saved:before{content:"\e173"}.yasgui .glyphicon-floppy-remove:before{content:"\e174"}.yasgui .glyphicon-floppy-save:before{content:"\e175"}.yasgui .glyphicon-floppy-open:before{content:"\e176"}.yasgui .glyphicon-credit-card:before{content:"\e177"}.yasgui .glyphicon-transfer:before{content:"\e178"}.yasgui .glyphicon-cutlery:before{content:"\e179"}.yasgui .glyphicon-header:before{content:"\e180"}.yasgui .glyphicon-compressed:before{content:"\e181"}.yasgui .glyphicon-earphone:before{content:"\e182"}.yasgui .glyphicon-phone-alt:before{content:"\e183"}.yasgui .glyphicon-tower:before{content:"\e184"}.yasgui .glyphicon-stats:before{content:"\e185"}.yasgui .glyphicon-sd-video:before{content:"\e186"}.yasgui .glyphicon-hd-video:before{content:"\e187"}.yasgui .glyphicon-subtitles:before{content:"\e188"}.yasgui .glyphicon-sound-stereo:before{content:"\e189"}.yasgui .glyphicon-sound-dolby:before{content:"\e190"}.yasgui .glyphicon-sound-5-1:before{content:"\e191"}.yasgui .glyphicon-sound-6-1:before{content:"\e192"}.yasgui .glyphicon-sound-7-1:before{content:"\e193"}.yasgui .glyphicon-copyright-mark:before{content:"\e194"}.yasgui .glyphicon-registration-mark:before{content:"\e195"}.yasgui .glyphicon-cloud-download:before{content:"\e197"}.yasgui .glyphicon-cloud-upload:before{content:"\e198"}.yasgui .glyphicon-tree-conifer:before{content:"\e199"}.yasgui .glyphicon-tree-deciduous:before{content:"\e200"}.yasgui *,.yasgui :after,.yasgui :before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui html{font-size:10px;-webkit-tap-highlight-color:transparent}.yasgui body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857;color:#333;background-color:#fff}.yasgui button,.yasgui input,.yasgui select,.yasgui textarea{font-family:inherit;font-size:inherit;line-height:inherit}.yasgui a{color:#337ab7;text-decoration:none}.yasgui a:focus,.yasgui a:hover{color:#23527c;text-decoration:underline}.yasgui a:focus{outline:dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.yasgui figure{margin:0}.yasgui img{vertical-align:middle}.yasgui .img-responsive{display:block;max-width:100%;height:auto}.yasgui .img-rounded{border-radius:6px}.yasgui .img-thumbnail{padding:4px;line-height:1.42857;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out;display:inline-block;max-width:100%;height:auto}.yasgui .img-circle{border-radius:50%}.yasgui hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.yasgui .sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);border:0}.yasgui .sr-only-focusable:active,.yasgui .sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}.yasgui .h1,.yasgui .h2,.yasgui .h3,.yasgui .h4,.yasgui .h5,.yasgui .h6,.yasgui h1,.yasgui h2,.yasgui h3,.yasgui h4,.yasgui h5,.yasgui h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.yasgui .h1 .small,.yasgui .h1 small,.yasgui .h2 .small,.yasgui .h2 small,.yasgui .h3 .small,.yasgui .h3 small,.yasgui .h4 .small,.yasgui .h4 small,.yasgui .h5 .small,.yasgui .h5 small,.yasgui .h6 .small,.yasgui .h6 small,.yasgui h1 .small,.yasgui h1 small,.yasgui h2 .small,.yasgui h2 small,.yasgui h3 .small,.yasgui h3 small,.yasgui h4 .small,.yasgui h4 small,.yasgui h5 .small,.yasgui h5 small,.yasgui h6 .small,.yasgui h6 small{font-weight:400;line-height:1;color:#777}.yasgui .h1,.yasgui .h2,.yasgui .h3,.yasgui h1,.yasgui h2,.yasgui h3{margin-top:20px;margin-bottom:10px}.yasgui .h1 .small,.yasgui .h1 small,.yasgui .h2 .small,.yasgui .h2 small,.yasgui .h3 .small,.yasgui .h3 small,.yasgui h1 .small,.yasgui h1 small,.yasgui h2 .small,.yasgui h2 small,.yasgui h3 .small,.yasgui h3 small{font-size:65%}.yasgui .h4,.yasgui .h5,.yasgui .h6,.yasgui h4,.yasgui h5,.yasgui h6{margin-top:10px;margin-bottom:10px}.yasgui .h4 .small,.yasgui .h4 small,.yasgui .h5 .small,.yasgui .h5 small,.yasgui .h6 .small,.yasgui .h6 small,.yasgui h4 .small,.yasgui h4 small,.yasgui h5 .small,.yasgui h5 small,.yasgui h6 .small,.yasgui h6 small{font-size:75%}.yasgui .h1,.yasgui h1{font-size:36px}.yasgui .h2,.yasgui h2{font-size:30px}.yasgui .h3,.yasgui h3{font-size:24px}.yasgui .h4,.yasgui h4{font-size:18px}.yasgui .h5,.yasgui h5{font-size:14px}.yasgui .h6,.yasgui h6{font-size:12px}.yasgui p{margin:0 0 10px}.yasgui .lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.yasgui .lead{font-size:21px}}.yasgui .small,.yasgui small{font-size:85%}.yasgui .mark,.yasgui mark{background-color:#fcf8e3;padding:.2em}.yasgui .text-left{text-align:left}.yasgui .text-right{text-align:right}.yasgui .text-center{text-align:center}.yasgui .text-justify{text-align:justify}.yasgui .text-nowrap{white-space:nowrap}.yasgui .text-lowercase{text-transform:lowercase}.yasgui .text-uppercase{text-transform:uppercase}.yasgui .text-capitalize{text-transform:capitalize}.yasgui .text-muted{color:#777}.yasgui .text-primary{color:#337ab7}.yasgui a.text-primary:hover{color:#286090}.yasgui .text-success{color:#3c763d}.yasgui a.text-success:hover{color:#2b542c}.yasgui .text-info{color:#31708f}.yasgui a.text-info:hover{color:#245269}.yasgui .text-warning{color:#8a6d3b}.yasgui a.text-warning:hover{color:#66512c}.yasgui .text-danger{color:#a94442}.yasgui a.text-danger:hover{color:#843534}.yasgui .bg-primary{color:#fff;background-color:#337ab7}.yasgui a.bg-primary:hover{background-color:#286090}.yasgui .bg-success{background-color:#dff0d8}.yasgui a.bg-success:hover{background-color:#c1e2b3}.yasgui .bg-info{background-color:#d9edf7}.yasgui a.bg-info:hover{background-color:#afd9ee}.yasgui .bg-warning{background-color:#fcf8e3}.yasgui a.bg-warning:hover{background-color:#f7ecb5}.yasgui .bg-danger{background-color:#f2dede}.yasgui a.bg-danger:hover{background-color:#e4b9b9}.yasgui .page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}.yasgui ol,.yasgui ul{margin-top:0;margin-bottom:10px}.yasgui ol ol,.yasgui ol ul,.yasgui ul ol,.yasgui ul ul{margin-bottom:0}.yasgui .list-unstyled{padding-left:0;list-style:none}.yasgui .list-inline{padding-left:0;list-style:none;margin-left:-5px}.yasgui .list-inline>li{display:inline-block;padding-left:5px;padding-right:5px}.yasgui dl{margin-top:0;margin-bottom:20px}.yasgui dd,.yasgui dt{line-height:1.42857}.yasgui dt{font-weight:700}.yasgui dd{margin-left:0}.yasgui .dl-horizontal dd:after,.yasgui .dl-horizontal dd:before{content:" ";display:table}.yasgui .dl-horizontal dd:after{clear:both}@media (min-width:768px){.yasgui .dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.yasgui .dl-horizontal dd{margin-left:180px}}.yasgui abbr[data-original-title],.yasgui abbr[title]{cursor:help;border-bottom:1px dotted #777}.yasgui .initialism{font-size:90%;text-transform:uppercase}.yasgui blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}.yasgui blockquote ol:last-child,.yasgui blockquote p:last-child,.yasgui blockquote ul:last-child{margin-bottom:0}.yasgui blockquote .small,.yasgui blockquote footer,.yasgui blockquote small{display:block;font-size:80%;line-height:1.42857;color:#777}.yasgui blockquote .small:before,.yasgui blockquote footer:before,.yasgui blockquote small:before{content:'\2014 \00A0'}.yasgui .blockquote-reverse,.yasgui blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}.yasgui .blockquote-reverse .small:before,.yasgui .blockquote-reverse footer:before,.yasgui .blockquote-reverse small:before,.yasgui blockquote.pull-right .small:before,.yasgui blockquote.pull-right footer:before,.yasgui blockquote.pull-right small:before{content:''}.yasgui .blockquote-reverse .small:after,.yasgui .blockquote-reverse footer:after,.yasgui .blockquote-reverse small:after,.yasgui blockquote.pull-right .small:after,.yasgui blockquote.pull-right footer:after,.yasgui blockquote.pull-right small:after{content:'\00A0 \2014'}.yasgui address{margin-bottom:20px;font-style:normal;line-height:1.42857}.yasgui code,.yasgui kbd,.yasgui pre,.yasgui samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}.yasgui code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}.yasgui kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}.yasgui kbd kbd{padding:0;font-size:100%;font-weight:700;box-shadow:none}.yasgui pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}.yasgui pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.yasgui .pre-scrollable{max-height:340px;overflow-y:scroll}.yasgui .container{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.yasgui .container:after,.yasgui .container:before{content:" ";display:table}.yasgui .container:after{clear:both}@media (min-width:768px){.yasgui .container{width:750px}}@media (min-width:992px){.yasgui .container{width:970px}}@media (min-width:1200px){.yasgui .container{width:1170px}}.yasgui .container-fluid{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.yasgui .container-fluid:after,.yasgui .container-fluid:before{content:" ";display:table}.yasgui .container-fluid:after{clear:both}.yasgui .row{margin-left:-15px;margin-right:-15px}.yasgui .row:after,.yasgui .row:before{content:" ";display:table}.yasgui .row:after{clear:both}.yasgui .col-lg-1,.yasgui .col-lg-10,.yasgui .col-lg-11,.yasgui .col-lg-12,.yasgui .col-lg-2,.yasgui .col-lg-3,.yasgui .col-lg-4,.yasgui .col-lg-5,.yasgui .col-lg-6,.yasgui .col-lg-7,.yasgui .col-lg-8,.yasgui .col-lg-9,.yasgui .col-md-1,.yasgui .col-md-10,.yasgui .col-md-11,.yasgui .col-md-12,.yasgui .col-md-2,.yasgui .col-md-3,.yasgui .col-md-4,.yasgui .col-md-5,.yasgui .col-md-6,.yasgui .col-md-7,.yasgui .col-md-8,.yasgui .col-md-9,.yasgui .col-sm-1,.yasgui .col-sm-10,.yasgui .col-sm-11,.yasgui .col-sm-12,.yasgui .col-sm-2,.yasgui .col-sm-3,.yasgui .col-sm-4,.yasgui .col-sm-5,.yasgui .col-sm-6,.yasgui .col-sm-7,.yasgui .col-sm-8,.yasgui .col-sm-9,.yasgui .col-xs-1,.yasgui .col-xs-10,.yasgui .col-xs-11,.yasgui .col-xs-12,.yasgui .col-xs-2,.yasgui .col-xs-3,.yasgui .col-xs-4,.yasgui .col-xs-5,.yasgui .col-xs-6,.yasgui .col-xs-7,.yasgui .col-xs-8,.yasgui .col-xs-9{position:relative;min-height:1px;padding-left:15px;padding-right:15px}.yasgui .col-xs-1,.yasgui .col-xs-10,.yasgui .col-xs-11,.yasgui .col-xs-12,.yasgui .col-xs-2,.yasgui .col-xs-3,.yasgui .col-xs-4,.yasgui .col-xs-5,.yasgui .col-xs-6,.yasgui .col-xs-7,.yasgui .col-xs-8,.yasgui .col-xs-9{float:left}.yasgui .col-xs-1{width:8.33333%}.yasgui .col-xs-2{width:16.66667%}.yasgui .col-xs-3{width:25%}.yasgui .col-xs-4{width:33.33333%}.yasgui .col-xs-5{width:41.66667%}.yasgui .col-xs-6{width:50%}.yasgui .col-xs-7{width:58.33333%}.yasgui .col-xs-8{width:66.66667%}.yasgui .col-xs-9{width:75%}.yasgui .col-xs-10{width:83.33333%}.yasgui .col-xs-11{width:91.66667%}.yasgui .col-xs-12{width:100%}.yasgui .col-xs-pull-0{right:auto}.yasgui .col-xs-pull-1{right:8.33333%}.yasgui .col-xs-pull-2{right:16.66667%}.yasgui .col-xs-pull-3{right:25%}.yasgui .col-xs-pull-4{right:33.33333%}.yasgui .col-xs-pull-5{right:41.66667%}.yasgui .col-xs-pull-6{right:50%}.yasgui .col-xs-pull-7{right:58.33333%}.yasgui .col-xs-pull-8{right:66.66667%}.yasgui .col-xs-pull-9{right:75%}.yasgui .col-xs-pull-10{right:83.33333%}.yasgui .col-xs-pull-11{right:91.66667%}.yasgui .col-xs-pull-12{right:100%}.yasgui .col-xs-push-0{left:auto}.yasgui .col-xs-push-1{left:8.33333%}.yasgui .col-xs-push-2{left:16.66667%}.yasgui .col-xs-push-3{left:25%}.yasgui .col-xs-push-4{left:33.33333%}.yasgui .col-xs-push-5{left:41.66667%}.yasgui .col-xs-push-6{left:50%}.yasgui .col-xs-push-7{left:58.33333%}.yasgui .col-xs-push-8{left:66.66667%}.yasgui .col-xs-push-9{left:75%}.yasgui .col-xs-push-10{left:83.33333%}.yasgui .col-xs-push-11{left:91.66667%}.yasgui .col-xs-push-12{left:100%}.yasgui .col-xs-offset-0{margin-left:0}.yasgui .col-xs-offset-1{margin-left:8.33333%}.yasgui .col-xs-offset-2{margin-left:16.66667%}.yasgui .col-xs-offset-3{margin-left:25%}.yasgui .col-xs-offset-4{margin-left:33.33333%}.yasgui .col-xs-offset-5{margin-left:41.66667%}.yasgui .col-xs-offset-6{margin-left:50%}.yasgui .col-xs-offset-7{margin-left:58.33333%}.yasgui .col-xs-offset-8{margin-left:66.66667%}.yasgui .col-xs-offset-9{margin-left:75%}.yasgui .col-xs-offset-10{margin-left:83.33333%}.yasgui .col-xs-offset-11{margin-left:91.66667%}.yasgui .col-xs-offset-12{margin-left:100%}@media (min-width:768px){.yasgui .col-sm-1,.yasgui .col-sm-10,.yasgui .col-sm-11,.yasgui .col-sm-12,.yasgui .col-sm-2,.yasgui .col-sm-3,.yasgui .col-sm-4,.yasgui .col-sm-5,.yasgui .col-sm-6,.yasgui .col-sm-7,.yasgui .col-sm-8,.yasgui .col-sm-9{float:left}.yasgui .col-sm-1{width:8.33333%}.yasgui .col-sm-2{width:16.66667%}.yasgui .col-sm-3{width:25%}.yasgui .col-sm-4{width:33.33333%}.yasgui .col-sm-5{width:41.66667%}.yasgui .col-sm-6{width:50%}.yasgui .col-sm-7{width:58.33333%}.yasgui .col-sm-8{width:66.66667%}.yasgui .col-sm-9{width:75%}.yasgui .col-sm-10{width:83.33333%}.yasgui .col-sm-11{width:91.66667%}.yasgui .col-sm-12{width:100%}.yasgui .col-sm-pull-0{right:auto}.yasgui .col-sm-pull-1{right:8.33333%}.yasgui .col-sm-pull-2{right:16.66667%}.yasgui .col-sm-pull-3{right:25%}.yasgui .col-sm-pull-4{right:33.33333%}.yasgui .col-sm-pull-5{right:41.66667%}.yasgui .col-sm-pull-6{right:50%}.yasgui .col-sm-pull-7{right:58.33333%}.yasgui .col-sm-pull-8{right:66.66667%}.yasgui .col-sm-pull-9{right:75%}.yasgui .col-sm-pull-10{right:83.33333%}.yasgui .col-sm-pull-11{right:91.66667%}.yasgui .col-sm-pull-12{right:100%}.yasgui .col-sm-push-0{left:auto}.yasgui .col-sm-push-1{left:8.33333%}.yasgui .col-sm-push-2{left:16.66667%}.yasgui .col-sm-push-3{left:25%}.yasgui .col-sm-push-4{left:33.33333%}.yasgui .col-sm-push-5{left:41.66667%}.yasgui .col-sm-push-6{left:50%}.yasgui .col-sm-push-7{left:58.33333%}.yasgui .col-sm-push-8{left:66.66667%}.yasgui .col-sm-push-9{left:75%}.yasgui .col-sm-push-10{left:83.33333%}.yasgui .col-sm-push-11{left:91.66667%}.yasgui .col-sm-push-12{left:100%}.yasgui .col-sm-offset-0{margin-left:0}.yasgui .col-sm-offset-1{margin-left:8.33333%}.yasgui .col-sm-offset-2{margin-left:16.66667%}.yasgui .col-sm-offset-3{margin-left:25%}.yasgui .col-sm-offset-4{margin-left:33.33333%}.yasgui .col-sm-offset-5{margin-left:41.66667%}.yasgui .col-sm-offset-6{margin-left:50%}.yasgui .col-sm-offset-7{margin-left:58.33333%}.yasgui .col-sm-offset-8{margin-left:66.66667%}.yasgui .col-sm-offset-9{margin-left:75%}.yasgui .col-sm-offset-10{margin-left:83.33333%}.yasgui .col-sm-offset-11{margin-left:91.66667%}.yasgui .col-sm-offset-12{margin-left:100%}}@media (min-width:992px){.yasgui .col-md-1,.yasgui .col-md-10,.yasgui .col-md-11,.yasgui .col-md-12,.yasgui .col-md-2,.yasgui .col-md-3,.yasgui .col-md-4,.yasgui .col-md-5,.yasgui .col-md-6,.yasgui .col-md-7,.yasgui .col-md-8,.yasgui .col-md-9{float:left}.yasgui .col-md-1{width:8.33333%}.yasgui .col-md-2{width:16.66667%}.yasgui .col-md-3{width:25%}.yasgui .col-md-4{width:33.33333%}.yasgui .col-md-5{width:41.66667%}.yasgui .col-md-6{width:50%}.yasgui .col-md-7{width:58.33333%}.yasgui .col-md-8{width:66.66667%}.yasgui .col-md-9{width:75%}.yasgui .col-md-10{width:83.33333%}.yasgui .col-md-11{width:91.66667%}.yasgui .col-md-12{width:100%}.yasgui .col-md-pull-0{right:auto}.yasgui .col-md-pull-1{right:8.33333%}.yasgui .col-md-pull-2{right:16.66667%}.yasgui .col-md-pull-3{right:25%}.yasgui .col-md-pull-4{right:33.33333%}.yasgui .col-md-pull-5{right:41.66667%}.yasgui .col-md-pull-6{right:50%}.yasgui .col-md-pull-7{right:58.33333%}.yasgui .col-md-pull-8{right:66.66667%}.yasgui .col-md-pull-9{right:75%}.yasgui .col-md-pull-10{right:83.33333%}.yasgui .col-md-pull-11{right:91.66667%}.yasgui .col-md-pull-12{right:100%}.yasgui .col-md-push-0{left:auto}.yasgui .col-md-push-1{left:8.33333%}.yasgui .col-md-push-2{left:16.66667%}.yasgui .col-md-push-3{left:25%}.yasgui .col-md-push-4{left:33.33333%}.yasgui .col-md-push-5{left:41.66667%}.yasgui .col-md-push-6{left:50%}.yasgui .col-md-push-7{left:58.33333%}.yasgui .col-md-push-8{left:66.66667%}.yasgui .col-md-push-9{left:75%}.yasgui .col-md-push-10{left:83.33333%}.yasgui .col-md-push-11{left:91.66667%}.yasgui .col-md-push-12{left:100%}.yasgui .col-md-offset-0{margin-left:0}.yasgui .col-md-offset-1{margin-left:8.33333%}.yasgui .col-md-offset-2{margin-left:16.66667%}.yasgui .col-md-offset-3{margin-left:25%}.yasgui .col-md-offset-4{margin-left:33.33333%}.yasgui .col-md-offset-5{margin-left:41.66667%}.yasgui .col-md-offset-6{margin-left:50%}.yasgui .col-md-offset-7{margin-left:58.33333%}.yasgui .col-md-offset-8{margin-left:66.66667%}.yasgui .col-md-offset-9{margin-left:75%}.yasgui .col-md-offset-10{margin-left:83.33333%}.yasgui .col-md-offset-11{margin-left:91.66667%}.yasgui .col-md-offset-12{margin-left:100%}}@media (min-width:1200px){.yasgui .col-lg-1,.yasgui .col-lg-10,.yasgui .col-lg-11,.yasgui .col-lg-12,.yasgui .col-lg-2,.yasgui .col-lg-3,.yasgui .col-lg-4,.yasgui .col-lg-5,.yasgui .col-lg-6,.yasgui .col-lg-7,.yasgui .col-lg-8,.yasgui .col-lg-9{float:left}.yasgui .col-lg-1{width:8.33333%}.yasgui .col-lg-2{width:16.66667%}.yasgui .col-lg-3{width:25%}.yasgui .col-lg-4{width:33.33333%}.yasgui .col-lg-5{width:41.66667%}.yasgui .col-lg-6{width:50%}.yasgui .col-lg-7{width:58.33333%}.yasgui .col-lg-8{width:66.66667%}.yasgui .col-lg-9{width:75%}.yasgui .col-lg-10{width:83.33333%}.yasgui .col-lg-11{width:91.66667%}.yasgui .col-lg-12{width:100%}.yasgui .col-lg-pull-0{right:auto}.yasgui .col-lg-pull-1{right:8.33333%}.yasgui .col-lg-pull-2{right:16.66667%}.yasgui .col-lg-pull-3{right:25%}.yasgui .col-lg-pull-4{right:33.33333%}.yasgui .col-lg-pull-5{right:41.66667%}.yasgui .col-lg-pull-6{right:50%}.yasgui .col-lg-pull-7{right:58.33333%}.yasgui .col-lg-pull-8{right:66.66667%}.yasgui .col-lg-pull-9{right:75%}.yasgui .col-lg-pull-10{right:83.33333%}.yasgui .col-lg-pull-11{right:91.66667%}.yasgui .col-lg-pull-12{right:100%}.yasgui .col-lg-push-0{left:auto}.yasgui .col-lg-push-1{left:8.33333%}.yasgui .col-lg-push-2{left:16.66667%}.yasgui .col-lg-push-3{left:25%}.yasgui .col-lg-push-4{left:33.33333%}.yasgui .col-lg-push-5{left:41.66667%}.yasgui .col-lg-push-6{left:50%}.yasgui .col-lg-push-7{left:58.33333%}.yasgui .col-lg-push-8{left:66.66667%}.yasgui .col-lg-push-9{left:75%}.yasgui .col-lg-push-10{left:83.33333%}.yasgui .col-lg-push-11{left:91.66667%}.yasgui .col-lg-push-12{left:100%}.yasgui .col-lg-offset-0{margin-left:0}.yasgui .col-lg-offset-1{margin-left:8.33333%}.yasgui .col-lg-offset-2{margin-left:16.66667%}.yasgui .col-lg-offset-3{margin-left:25%}.yasgui .col-lg-offset-4{margin-left:33.33333%}.yasgui .col-lg-offset-5{margin-left:41.66667%}.yasgui .col-lg-offset-6{margin-left:50%}.yasgui .col-lg-offset-7{margin-left:58.33333%}.yasgui .col-lg-offset-8{margin-left:66.66667%}.yasgui .col-lg-offset-9{margin-left:75%}.yasgui .col-lg-offset-10{margin-left:83.33333%}.yasgui .col-lg-offset-11{margin-left:91.66667%}.yasgui .col-lg-offset-12{margin-left:100%}}.yasgui table{background-color:transparent}.yasgui caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}.yasgui th{text-align:left}.yasgui .table{width:100%;max-width:100%;margin-bottom:20px}.yasgui .table>tbody>tr>td,.yasgui .table>tbody>tr>th,.yasgui .table>tfoot>tr>td,.yasgui .table>tfoot>tr>th,.yasgui .table>thead>tr>td,.yasgui .table>thead>tr>th{padding:8px;line-height:1.42857;vertical-align:top;border-top:1px solid #ddd}.yasgui .table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.yasgui .table>caption+thead>tr:first-child>td,.yasgui .table>caption+thead>tr:first-child>th,.yasgui .table>colgroup+thead>tr:first-child>td,.yasgui .table>colgroup+thead>tr:first-child>th,.yasgui .table>thead:first-child>tr:first-child>td,.yasgui .table>thead:first-child>tr:first-child>th{border-top:0}.yasgui .table>tbody+tbody{border-top:2px solid #ddd}.yasgui .table .table{background-color:#fff}.yasgui .table-condensed>tbody>tr>td,.yasgui .table-condensed>tbody>tr>th,.yasgui .table-condensed>tfoot>tr>td,.yasgui .table-condensed>tfoot>tr>th,.yasgui .table-condensed>thead>tr>td,.yasgui .table-condensed>thead>tr>th{padding:5px}.yasgui .table-bordered,.yasgui .table-bordered>tbody>tr>td,.yasgui .table-bordered>tbody>tr>th,.yasgui .table-bordered>tfoot>tr>td,.yasgui .table-bordered>tfoot>tr>th,.yasgui .table-bordered>thead>tr>td,.yasgui .table-bordered>thead>tr>th{border:1px solid #ddd}.yasgui .table-bordered>thead>tr>td,.yasgui .table-bordered>thead>tr>th{border-bottom-width:2px}.yasgui .table-striped>tbody>tr:nth-child(odd){background-color:#f9f9f9}.yasgui .table-hover>tbody>tr:hover{background-color:#f5f5f5}.yasgui table col[class*=col-]{position:static;float:none;display:table-column}.yasgui table td[class*=col-],.yasgui table th[class*=col-]{position:static;float:none;display:table-cell}.yasgui .table>tbody>tr.active>td,.yasgui .table>tbody>tr.active>th,.yasgui .table>tbody>tr>td.active,.yasgui .table>tbody>tr>th.active,.yasgui .table>tfoot>tr.active>td,.yasgui .table>tfoot>tr.active>th,.yasgui .table>tfoot>tr>td.active,.yasgui .table>tfoot>tr>th.active,.yasgui .table>thead>tr.active>td,.yasgui .table>thead>tr.active>th,.yasgui .table>thead>tr>td.active,.yasgui .table>thead>tr>th.active{background-color:#f5f5f5}.yasgui .table-hover>tbody>tr.active:hover>td,.yasgui .table-hover>tbody>tr.active:hover>th,.yasgui .table-hover>tbody>tr:hover>.active,.yasgui .table-hover>tbody>tr>td.active:hover,.yasgui .table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.yasgui .table>tbody>tr.success>td,.yasgui .table>tbody>tr.success>th,.yasgui .table>tbody>tr>td.success,.yasgui .table>tbody>tr>th.success,.yasgui .table>tfoot>tr.success>td,.yasgui .table>tfoot>tr.success>th,.yasgui .table>tfoot>tr>td.success,.yasgui .table>tfoot>tr>th.success,.yasgui .table>thead>tr.success>td,.yasgui .table>thead>tr.success>th,.yasgui .table>thead>tr>td.success,.yasgui .table>thead>tr>th.success{background-color:#dff0d8}.yasgui .table-hover>tbody>tr.success:hover>td,.yasgui .table-hover>tbody>tr.success:hover>th,.yasgui .table-hover>tbody>tr:hover>.success,.yasgui .table-hover>tbody>tr>td.success:hover,.yasgui .table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.yasgui .table>tbody>tr.info>td,.yasgui .table>tbody>tr.info>th,.yasgui .table>tbody>tr>td.info,.yasgui .table>tbody>tr>th.info,.yasgui .table>tfoot>tr.info>td,.yasgui .table>tfoot>tr.info>th,.yasgui .table>tfoot>tr>td.info,.yasgui .table>tfoot>tr>th.info,.yasgui .table>thead>tr.info>td,.yasgui .table>thead>tr.info>th,.yasgui .table>thead>tr>td.info,.yasgui .table>thead>tr>th.info{background-color:#d9edf7}.yasgui .table-hover>tbody>tr.info:hover>td,.yasgui .table-hover>tbody>tr.info:hover>th,.yasgui .table-hover>tbody>tr:hover>.info,.yasgui .table-hover>tbody>tr>td.info:hover,.yasgui .table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.yasgui .table>tbody>tr.warning>td,.yasgui .table>tbody>tr.warning>th,.yasgui .table>tbody>tr>td.warning,.yasgui .table>tbody>tr>th.warning,.yasgui .table>tfoot>tr.warning>td,.yasgui .table>tfoot>tr.warning>th,.yasgui .table>tfoot>tr>td.warning,.yasgui .table>tfoot>tr>th.warning,.yasgui .table>thead>tr.warning>td,.yasgui .table>thead>tr.warning>th,.yasgui .table>thead>tr>td.warning,.yasgui .table>thead>tr>th.warning{background-color:#fcf8e3}.yasgui .table-hover>tbody>tr.warning:hover>td,.yasgui .table-hover>tbody>tr.warning:hover>th,.yasgui .table-hover>tbody>tr:hover>.warning,.yasgui .table-hover>tbody>tr>td.warning:hover,.yasgui .table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.yasgui .table>tbody>tr.danger>td,.yasgui .table>tbody>tr.danger>th,.yasgui .table>tbody>tr>td.danger,.yasgui .table>tbody>tr>th.danger,.yasgui .table>tfoot>tr.danger>td,.yasgui .table>tfoot>tr.danger>th,.yasgui .table>tfoot>tr>td.danger,.yasgui .table>tfoot>tr>th.danger,.yasgui .table>thead>tr.danger>td,.yasgui .table>thead>tr.danger>th,.yasgui .table>thead>tr>td.danger,.yasgui .table>thead>tr>th.danger{background-color:#f2dede}.yasgui .table-hover>tbody>tr.danger:hover>td,.yasgui .table-hover>tbody>tr.danger:hover>th,.yasgui .table-hover>tbody>tr:hover>.danger,.yasgui .table-hover>tbody>tr>td.danger:hover,.yasgui .table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.yasgui .table-responsive{overflow-x:auto;min-height:.01%}@media screen and (max-width:767px){.yasgui .table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.yasgui .table-responsive>.table{margin-bottom:0}.yasgui .table-responsive>.table>tbody>tr>td,.yasgui .table-responsive>.table>tbody>tr>th,.yasgui .table-responsive>.table>tfoot>tr>td,.yasgui .table-responsive>.table>tfoot>tr>th,.yasgui .table-responsive>.table>thead>tr>td,.yasgui .table-responsive>.table>thead>tr>th{white-space:nowrap}.yasgui .table-responsive>.table-bordered{border:0}.yasgui .table-responsive>.table-bordered>tbody>tr>td:first-child,.yasgui .table-responsive>.table-bordered>tbody>tr>th:first-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>td:first-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>th:first-child,.yasgui .table-responsive>.table-bordered>thead>tr>td:first-child,.yasgui .table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.yasgui .table-responsive>.table-bordered>tbody>tr>td:last-child,.yasgui .table-responsive>.table-bordered>tbody>tr>th:last-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>td:last-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>th:last-child,.yasgui .table-responsive>.table-bordered>thead>tr>td:last-child,.yasgui .table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.yasgui .table-responsive>.table-bordered>tbody>tr:last-child>td,.yasgui .table-responsive>.table-bordered>tbody>tr:last-child>th,.yasgui .table-responsive>.table-bordered>tfoot>tr:last-child>td,.yasgui .table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}.yasgui fieldset{padding:0;margin:0;border:0;min-width:0}.yasgui legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}.yasgui label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}.yasgui input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui input[type=radio],.yasgui input[type=checkbox]{margin:4px 0 0;line-height:normal}.yasgui input[type=file]{display:block}.yasgui input[type=range]{display:block;width:100%}.yasgui select[multiple],.yasgui select[size]{height:auto}.yasgui input[type=radio]:focus,.yasgui input[type=file]:focus,.yasgui input[type=checkbox]:focus{outline:dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.yasgui output{display:block;padding-top:7px;font-size:14px;line-height:1.42857;color:#555}.yasgui .form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.yasgui .form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.yasgui .form-control::-moz-placeholder{color:#999;opacity:1}.yasgui .form-control:-ms-input-placeholder{color:#999}.yasgui .form-control::-webkit-input-placeholder{color:#999}.yasgui .form-control[disabled],.yasgui .form-control[readonly],fieldset[disabled] .yasgui .form-control{cursor:not-allowed;background-color:#eee;opacity:1}.yasgui textarea.form-control{height:auto}.yasgui input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){.yasgui input[type=date],.yasgui input[type=time],.yasgui input[type=datetime-local],.yasgui input[type=month]{line-height:34px}.yasgui .input-group-sm>.input-group-btn>input[type=date].btn,.yasgui .input-group-sm>.input-group-btn>input[type=time].btn,.yasgui .input-group-sm>.input-group-btn>input[type=datetime-local].btn,.yasgui .input-group-sm>.input-group-btn>input[type=month].btn,.yasgui .input-group-sm>input[type=date].form-control,.yasgui .input-group-sm>input[type=date].input-group-addon,.yasgui .input-group-sm>input[type=time].form-control,.yasgui .input-group-sm>input[type=time].input-group-addon,.yasgui .input-group-sm>input[type=datetime-local].form-control,.yasgui .input-group-sm>input[type=datetime-local].input-group-addon,.yasgui .input-group-sm>input[type=month].form-control,.yasgui .input-group-sm>input[type=month].input-group-addon,.yasgui input[type=date].input-sm,.yasgui input[type=time].input-sm,.yasgui input[type=datetime-local].input-sm,.yasgui input[type=month].input-sm{line-height:30px}.yasgui .input-group-lg>.input-group-btn>input[type=date].btn,.yasgui .input-group-lg>.input-group-btn>input[type=time].btn,.yasgui .input-group-lg>.input-group-btn>input[type=datetime-local].btn,.yasgui .input-group-lg>.input-group-btn>input[type=month].btn,.yasgui .input-group-lg>input[type=date].form-control,.yasgui .input-group-lg>input[type=date].input-group-addon,.yasgui .input-group-lg>input[type=time].form-control,.yasgui .input-group-lg>input[type=time].input-group-addon,.yasgui .input-group-lg>input[type=datetime-local].form-control,.yasgui .input-group-lg>input[type=datetime-local].input-group-addon,.yasgui .input-group-lg>input[type=month].form-control,.yasgui .input-group-lg>input[type=month].input-group-addon,.yasgui input[type=date].input-lg,.yasgui input[type=time].input-lg,.yasgui input[type=datetime-local].input-lg,.yasgui input[type=month].input-lg{line-height:46px}}.yasgui .form-group{margin-bottom:15px}.yasgui .checkbox,.yasgui .radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.yasgui .checkbox label,.yasgui .radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.yasgui .checkbox input[type=checkbox],.yasgui .checkbox-inline input[type=checkbox],.yasgui .radio input[type=radio],.yasgui .radio-inline input[type=radio]{position:absolute;margin-left:-20px}.yasgui .checkbox+.checkbox,.yasgui .radio+.radio{margin-top:-5px}.yasgui .checkbox-inline,.yasgui .radio-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.yasgui .checkbox-inline+.checkbox-inline,.yasgui .radio-inline+.radio-inline{margin-top:0;margin-left:10px}.yasgui .checkbox-inline.disabled,.yasgui .checkbox.disabled label,.yasgui .radio-inline.disabled,.yasgui .radio.disabled label,.yasgui input[type=radio].disabled,.yasgui input[type=radio][disabled],.yasgui input[type=checkbox].disabled,.yasgui input[type=checkbox][disabled],fieldset[disabled] .yasgui .checkbox label,fieldset[disabled] .yasgui .checkbox-inline,fieldset[disabled] .yasgui .radio label,fieldset[disabled] .yasgui .radio-inline,fieldset[disabled] .yasgui input[type=radio],fieldset[disabled] .yasgui input[type=checkbox]{cursor:not-allowed}.yasgui .form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.yasgui .form-control-static.input-lg,.yasgui .form-control-static.input-sm,.yasgui .input-group-lg>.form-control-static.form-control,.yasgui .input-group-lg>.form-control-static.input-group-addon,.yasgui .input-group-lg>.input-group-btn>.form-control-static.btn,.yasgui .input-group-sm>.form-control-static.form-control,.yasgui .input-group-sm>.form-control-static.input-group-addon,.yasgui .input-group-sm>.input-group-btn>.form-control-static.btn{padding-left:0;padding-right:0}.yasgui .form-group-sm .form-control,.yasgui .input-group-sm>.form-control,.yasgui .input-group-sm>.input-group-addon,.yasgui .input-group-sm>.input-group-btn>.btn,.yasgui .input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.yasgui .form-group-sm .form-control,.yasgui .input-group-sm>.input-group-btn>select.btn,.yasgui .input-group-sm>select.form-control,.yasgui .input-group-sm>select.input-group-addon,.yasgui select.input-sm{height:30px;line-height:30px}.yasgui .form-group-sm .form-control,.yasgui .input-group-sm>.input-group-btn>select[multiple].btn,.yasgui .input-group-sm>.input-group-btn>textarea.btn,.yasgui .input-group-sm>select[multiple].form-control,.yasgui .input-group-sm>select[multiple].input-group-addon,.yasgui .input-group-sm>textarea.form-control,.yasgui .input-group-sm>textarea.input-group-addon,.yasgui select[multiple].input-sm,.yasgui textarea.input-sm{height:auto}.yasgui .form-group-lg .form-control,.yasgui .input-group-lg>.form-control,.yasgui .input-group-lg>.input-group-addon,.yasgui .input-group-lg>.input-group-btn>.btn,.yasgui .input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.yasgui .form-group-lg .form-control,.yasgui .input-group-lg>.input-group-btn>select.btn,.yasgui .input-group-lg>select.form-control,.yasgui .input-group-lg>select.input-group-addon,.yasgui select.input-lg{height:46px;line-height:46px}.yasgui .form-group-lg .form-control,.yasgui .input-group-lg>.input-group-btn>select[multiple].btn,.yasgui .input-group-lg>.input-group-btn>textarea.btn,.yasgui .input-group-lg>select[multiple].form-control,.yasgui .input-group-lg>select[multiple].input-group-addon,.yasgui .input-group-lg>textarea.form-control,.yasgui .input-group-lg>textarea.input-group-addon,.yasgui select[multiple].input-lg,.yasgui textarea.input-lg{height:auto}.yasgui .has-feedback{position:relative}.yasgui .has-feedback .form-control{padding-right:42.5px}.yasgui .form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.yasgui .input-group-lg>.form-control+.form-control-feedback,.yasgui .input-group-lg>.input-group-addon+.form-control-feedback,.yasgui .input-group-lg>.input-group-btn>.btn+.form-control-feedback,.yasgui .input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.yasgui .input-group-sm>.form-control+.form-control-feedback,.yasgui .input-group-sm>.input-group-addon+.form-control-feedback,.yasgui .input-group-sm>.input-group-btn>.btn+.form-control-feedback,.yasgui .input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.yasgui .has-success .checkbox,.yasgui .has-success .checkbox-inline,.yasgui .has-success .control-label,.yasgui .has-success .help-block,.yasgui .has-success .radio,.yasgui .has-success .radio-inline,.yasgui .has-success.checkbox label,.yasgui .has-success.checkbox-inline label,.yasgui .has-success.radio label,.yasgui .has-success.radio-inline label{color:#3c763d}.yasgui .has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.yasgui .has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.yasgui .has-success .form-control-feedback{color:#3c763d}.yasgui .has-warning .checkbox,.yasgui .has-warning .checkbox-inline,.yasgui .has-warning .control-label,.yasgui .has-warning .help-block,.yasgui .has-warning .radio,.yasgui .has-warning .radio-inline,.yasgui .has-warning.checkbox label,.yasgui .has-warning.checkbox-inline label,.yasgui .has-warning.radio label,.yasgui .has-warning.radio-inline label{color:#8a6d3b}.yasgui .has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.yasgui .has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.yasgui .has-warning .form-control-feedback{color:#8a6d3b}.yasgui .has-error .checkbox,.yasgui .has-error .checkbox-inline,.yasgui .has-error .control-label,.yasgui .has-error .help-block,.yasgui .has-error .radio,.yasgui .has-error .radio-inline,.yasgui .has-error.checkbox label,.yasgui .has-error.checkbox-inline label,.yasgui .has-error.radio label,.yasgui .has-error.radio-inline label{color:#a94442}.yasgui .has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.yasgui .has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.yasgui .has-error .form-control-feedback{color:#a94442}.yasgui .has-feedback label~.form-control-feedback{top:25px}.yasgui .has-feedback label.sr-only~.form-control-feedback{top:0}.yasgui .help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.yasgui .form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.yasgui .form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.yasgui .form-inline .form-control-static{display:inline-block}.yasgui .form-inline .input-group{display:inline-table;vertical-align:middle}.yasgui .form-inline .input-group .form-control,.yasgui .form-inline .input-group .input-group-addon,.yasgui .form-inline .input-group .input-group-btn{width:auto}.yasgui .form-inline .input-group>.form-control{width:100%}.yasgui .form-inline .control-label{margin-bottom:0;vertical-align:middle}.yasgui .form-inline .checkbox,.yasgui .form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.yasgui .form-inline .checkbox label,.yasgui .form-inline .radio label{padding-left:0}.yasgui .form-inline .checkbox input[type=checkbox],.yasgui .form-inline .radio input[type=radio]{position:relative;margin-left:0}.yasgui .form-inline .has-feedback .form-control-feedback{top:0}}.yasgui .form-horizontal .checkbox,.yasgui .form-horizontal .checkbox-inline,.yasgui .form-horizontal .radio,.yasgui .form-horizontal .radio-inline{margin-top:0;margin-bottom:0;padding-top:7px}.yasgui .form-horizontal .checkbox,.yasgui .form-horizontal .radio{min-height:27px}.yasgui .form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.yasgui .form-horizontal .form-group:after,.yasgui .form-horizontal .form-group:before{content:" ";display:table}.yasgui .form-horizontal .form-group:after{clear:both}@media (min-width:768px){.yasgui .form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}}.yasgui .form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.yasgui .form-horizontal .form-group-lg .control-label{padding-top:14.3px}}@media (min-width:768px){.yasgui .form-horizontal .form-group-sm .control-label{padding-top:6px}}.yasgui .btn{display:inline-block;margin-bottom:0;font-weight:400;text-align:center;vertical-align:middle;touch-action:manipulation;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;padding:6px 12px;font-size:14px;line-height:1.42857;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.yasgui .btn.active.focus,.yasgui .btn.active:focus,.yasgui .btn.focus,.yasgui .btn:active.focus,.yasgui .btn:active:focus,.yasgui .btn:focus{outline:dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.yasgui .btn.focus,.yasgui .btn:focus,.yasgui .btn:hover{color:#333;text-decoration:none}.yasgui .btn.active,.yasgui .btn:active{outline:0;background-image:none;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.yasgui .btn.disabled,.yasgui .btn[disabled],fieldset[disabled] .yasgui .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.yasgui .btn-default{color:#333;background-color:#fff;border-color:#ccc}.open>.yasgui .btn-default.dropdown-toggle,.yasgui .btn-default.active,.yasgui .btn-default.focus,.yasgui .btn-default:active,.yasgui .btn-default:focus,.yasgui .btn-default:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.open>.yasgui .btn-default.dropdown-toggle,.yasgui .btn-default.active,.yasgui .btn-default:active{background-image:none}.yasgui .btn-default.disabled,.yasgui .btn-default.disabled.active,.yasgui .btn-default.disabled.focus,.yasgui .btn-default.disabled:active,.yasgui .btn-default.disabled:focus,.yasgui .btn-default.disabled:hover,.yasgui .btn-default[disabled],.yasgui .btn-default[disabled].active,.yasgui .btn-default[disabled].focus,.yasgui .btn-default[disabled]:active,.yasgui .btn-default[disabled]:focus,.yasgui .btn-default[disabled]:hover,fieldset[disabled] .yasgui .btn-default,fieldset[disabled] .yasgui .btn-default.active,fieldset[disabled] .yasgui .btn-default.focus,fieldset[disabled] .yasgui .btn-default:active,fieldset[disabled] .yasgui .btn-default:focus,fieldset[disabled] .yasgui .btn-default:hover{background-color:#fff;border-color:#ccc}.yasgui .btn-default .badge{color:#fff;background-color:#333}.yasgui .btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.open>.yasgui .btn-primary.dropdown-toggle,.yasgui .btn-primary.active,.yasgui .btn-primary.focus,.yasgui .btn-primary:active,.yasgui .btn-primary:focus,.yasgui .btn-primary:hover{color:#fff;background-color:#286090;border-color:#204d74}.open>.yasgui .btn-primary.dropdown-toggle,.yasgui .btn-primary.active,.yasgui .btn-primary:active{background-image:none}.yasgui .btn-primary.disabled,.yasgui .btn-primary.disabled.active,.yasgui .btn-primary.disabled.focus,.yasgui .btn-primary.disabled:active,.yasgui .btn-primary.disabled:focus,.yasgui .btn-primary.disabled:hover,.yasgui .btn-primary[disabled],.yasgui .btn-primary[disabled].active,.yasgui .btn-primary[disabled].focus,.yasgui .btn-primary[disabled]:active,.yasgui .btn-primary[disabled]:focus,.yasgui .btn-primary[disabled]:hover,fieldset[disabled] .yasgui .btn-primary,fieldset[disabled] .yasgui .btn-primary.active,fieldset[disabled] .yasgui .btn-primary.focus,fieldset[disabled] .yasgui .btn-primary:active,fieldset[disabled] .yasgui .btn-primary:focus,fieldset[disabled] .yasgui .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.yasgui .btn-primary .badge{color:#337ab7;background-color:#fff}.yasgui .btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.open>.yasgui .btn-success.dropdown-toggle,.yasgui .btn-success.active,.yasgui .btn-success.focus,.yasgui .btn-success:active,.yasgui .btn-success:focus,.yasgui .btn-success:hover{color:#fff;background-color:#449d44;border-color:#398439}.open>.yasgui .btn-success.dropdown-toggle,.yasgui .btn-success.active,.yasgui .btn-success:active{background-image:none}.yasgui .btn-success.disabled,.yasgui .btn-success.disabled.active,.yasgui .btn-success.disabled.focus,.yasgui .btn-success.disabled:active,.yasgui .btn-success.disabled:focus,.yasgui .btn-success.disabled:hover,.yasgui .btn-success[disabled],.yasgui .btn-success[disabled].active,.yasgui .btn-success[disabled].focus,.yasgui .btn-success[disabled]:active,.yasgui .btn-success[disabled]:focus,.yasgui .btn-success[disabled]:hover,fieldset[disabled] .yasgui .btn-success,fieldset[disabled] .yasgui .btn-success.active,fieldset[disabled] .yasgui .btn-success.focus,fieldset[disabled] .yasgui .btn-success:active,fieldset[disabled] .yasgui .btn-success:focus,fieldset[disabled] .yasgui .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.yasgui .btn-success .badge{color:#5cb85c;background-color:#fff}.yasgui .btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.open>.yasgui .btn-info.dropdown-toggle,.yasgui .btn-info.active,.yasgui .btn-info.focus,.yasgui .btn-info:active,.yasgui .btn-info:focus,.yasgui .btn-info:hover{color:#fff;background-color:#31b0d5;border-color:#269abc}.open>.yasgui .btn-info.dropdown-toggle,.yasgui .btn-info.active,.yasgui .btn-info:active{background-image:none}.yasgui .btn-info.disabled,.yasgui .btn-info.disabled.active,.yasgui .btn-info.disabled.focus,.yasgui .btn-info.disabled:active,.yasgui .btn-info.disabled:focus,.yasgui .btn-info.disabled:hover,.yasgui .btn-info[disabled],.yasgui .btn-info[disabled].active,.yasgui .btn-info[disabled].focus,.yasgui .btn-info[disabled]:active,.yasgui .btn-info[disabled]:focus,.yasgui .btn-info[disabled]:hover,fieldset[disabled] .yasgui .btn-info,fieldset[disabled] .yasgui .btn-info.active,fieldset[disabled] .yasgui .btn-info.focus,fieldset[disabled] .yasgui .btn-info:active,fieldset[disabled] .yasgui .btn-info:focus,fieldset[disabled] .yasgui .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.yasgui .btn-info .badge{color:#5bc0de;background-color:#fff}.yasgui .btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.open>.yasgui .btn-warning.dropdown-toggle,.yasgui .btn-warning.active,.yasgui .btn-warning.focus,.yasgui .btn-warning:active,.yasgui .btn-warning:focus,.yasgui .btn-warning:hover{color:#fff;background-color:#ec971f;border-color:#d58512}.open>.yasgui .btn-warning.dropdown-toggle,.yasgui .btn-warning.active,.yasgui .btn-warning:active{background-image:none}.yasgui .btn-warning.disabled,.yasgui .btn-warning.disabled.active,.yasgui .btn-warning.disabled.focus,.yasgui .btn-warning.disabled:active,.yasgui .btn-warning.disabled:focus,.yasgui .btn-warning.disabled:hover,.yasgui .btn-warning[disabled],.yasgui .btn-warning[disabled].active,.yasgui .btn-warning[disabled].focus,.yasgui .btn-warning[disabled]:active,.yasgui .btn-warning[disabled]:focus,.yasgui .btn-warning[disabled]:hover,fieldset[disabled] .yasgui .btn-warning,fieldset[disabled] .yasgui .btn-warning.active,fieldset[disabled] .yasgui .btn-warning.focus,fieldset[disabled] .yasgui .btn-warning:active,fieldset[disabled] .yasgui .btn-warning:focus,fieldset[disabled] .yasgui .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.yasgui .btn-warning .badge{color:#f0ad4e;background-color:#fff}.yasgui .btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.open>.yasgui .btn-danger.dropdown-toggle,.yasgui .btn-danger.active,.yasgui .btn-danger.focus,.yasgui .btn-danger:active,.yasgui .btn-danger:focus,.yasgui .btn-danger:hover{color:#fff;background-color:#c9302c;border-color:#ac2925}.open>.yasgui .btn-danger.dropdown-toggle,.yasgui .btn-danger.active,.yasgui .btn-danger:active{background-image:none}.yasgui .btn-danger.disabled,.yasgui .btn-danger.disabled.active,.yasgui .btn-danger.disabled.focus,.yasgui .btn-danger.disabled:active,.yasgui .btn-danger.disabled:focus,.yasgui .btn-danger.disabled:hover,.yasgui .btn-danger[disabled],.yasgui .btn-danger[disabled].active,.yasgui .btn-danger[disabled].focus,.yasgui .btn-danger[disabled]:active,.yasgui .btn-danger[disabled]:focus,.yasgui .btn-danger[disabled]:hover,fieldset[disabled] .yasgui .btn-danger,fieldset[disabled] .yasgui .btn-danger.active,fieldset[disabled] .yasgui .btn-danger.focus,fieldset[disabled] .yasgui .btn-danger:active,fieldset[disabled] .yasgui .btn-danger:focus,fieldset[disabled] .yasgui .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.yasgui .btn-danger .badge{color:#d9534f;background-color:#fff}.yasgui .btn-link{color:#337ab7;font-weight:400;border-radius:0}.yasgui .btn-link,.yasgui .btn-link.active,.yasgui .btn-link:active,.yasgui .btn-link[disabled],fieldset[disabled] .yasgui .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.yasgui .btn-link,.yasgui .btn-link:active,.yasgui .btn-link:focus,.yasgui .btn-link:hover{border-color:transparent}.yasgui .btn-link:focus,.yasgui .btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.yasgui .btn-link[disabled]:focus,.yasgui .btn-link[disabled]:hover,fieldset[disabled] .yasgui .btn-link:focus,fieldset[disabled] .yasgui .btn-link:hover{color:#777;text-decoration:none}.yasgui .btn-group-lg>.btn,.yasgui .btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.yasgui .btn-group-sm>.btn,.yasgui .btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.yasgui .btn-group-xs>.btn,.yasgui .btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.yasgui .btn-block{display:block;width:100%}.yasgui .btn-block+.btn-block{margin-top:5px}.yasgui input[type=button].btn-block,.yasgui input[type=reset].btn-block,.yasgui input[type=submit].btn-block{width:100%}.yasgui .fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.yasgui .fade.in{opacity:1}.yasgui .collapse{display:none;visibility:hidden}.yasgui .collapse.in{display:block;visibility:visible}.yasgui tr.collapse.in{display:table-row}.yasgui tbody.collapse.in{display:table-row-group}.yasgui .collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-property:height,visibility;transition-property:height,visibility;-webkit-transition-duration:.35s;transition-duration:.35s;-webkit-transition-timing-function:ease;transition-timing-function:ease}.yasgui .caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.yasgui .dropdown{position:relative}.yasgui .dropdown-toggle:focus{outline:0}.yasgui .dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;font-size:14px;text-align:left;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175);background-clip:padding-box}.yasgui .dropdown-menu.pull-right{right:0;left:auto}.yasgui .dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.yasgui .dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857;color:#333;white-space:nowrap}.yasgui .dropdown-menu>li>a:focus,.yasgui .dropdown-menu>li>a:hover{text-decoration:none;color:#262626;background-color:#f5f5f5}.yasgui .dropdown-menu>.active>a,.yasgui .dropdown-menu>.active>a:focus,.yasgui .dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;outline:0;background-color:#337ab7}.yasgui .dropdown-menu>.disabled>a,.yasgui .dropdown-menu>.disabled>a:focus,.yasgui .dropdown-menu>.disabled>a:hover{color:#777}.yasgui .dropdown-menu>.disabled>a:focus,.yasgui .dropdown-menu>.disabled>a:hover{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);cursor:not-allowed}.yasgui .open>.dropdown-menu{display:block}.yasgui .open>a{outline:0}.yasgui .dropdown-menu-right{left:auto;right:0}.yasgui .dropdown-menu-left{left:0;right:auto}.yasgui .dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857;color:#777;white-space:nowrap}.yasgui .dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990}.yasgui .pull-right>.dropdown-menu{right:0;left:auto}.yasgui .dropup .caret,.yasgui .navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid;content:""}.yasgui .dropup .dropdown-menu,.yasgui .navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:768px){.yasgui .navbar-right .dropdown-menu{right:0;left:auto}.yasgui .navbar-right .dropdown-menu-left{left:0;right:auto}}.yasgui .btn-group,.yasgui .btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.yasgui .btn-group-vertical>.btn,.yasgui .btn-group>.btn{position:relative;float:left}.yasgui .btn-group-vertical>.btn.active,.yasgui .btn-group-vertical>.btn:active,.yasgui .btn-group-vertical>.btn:focus,.yasgui .btn-group-vertical>.btn:hover,.yasgui .btn-group>.btn.active,.yasgui .btn-group>.btn:active,.yasgui .btn-group>.btn:focus,.yasgui .btn-group>.btn:hover{z-index:2}.yasgui .btn-group .btn+.btn,.yasgui .btn-group .btn+.btn-group,.yasgui .btn-group .btn-group+.btn,.yasgui .btn-group .btn-group+.btn-group{margin-left:-1px}.yasgui .btn-toolbar{margin-left:-5px}.yasgui .btn-toolbar:after,.yasgui .btn-toolbar:before{content:" ";display:table}.yasgui .btn-toolbar:after{clear:both}.yasgui .btn-toolbar .btn-group,.yasgui .btn-toolbar .input-group{float:left}.yasgui .btn-toolbar>.btn,.yasgui .btn-toolbar>.btn-group,.yasgui .btn-toolbar>.input-group{margin-left:5px}.yasgui .btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.yasgui .btn-group>.btn:first-child{margin-left:0}.yasgui .btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.yasgui .btn-group>.btn:last-child:not(:first-child),.yasgui .btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.yasgui .btn-group>.btn-group{float:left}.yasgui .btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.yasgui .btn-group>.btn-group:first-child>.btn:last-child,.yasgui .btn-group>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-top-right-radius:0}.yasgui .btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.yasgui .btn-group .dropdown-toggle:active,.yasgui .btn-group.open .dropdown-toggle{outline:0}.yasgui .btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px}.yasgui .btn-group-lg.btn-group>.btn+.dropdown-toggle,.yasgui .btn-group>.btn-lg+.dropdown-toggle{padding-left:12px;padding-right:12px}.yasgui .btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.yasgui .btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.yasgui .btn .caret{margin-left:0}.yasgui .btn-group-lg>.btn .caret,.yasgui .btn-lg .caret{border-width:5px 5px 0}.yasgui .dropup .btn-group-lg>.btn .caret,.yasgui .dropup .btn-lg .caret{border-width:0 5px 5px}.yasgui .btn-group-vertical>.btn,.yasgui .btn-group-vertical>.btn-group,.yasgui .btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.yasgui .btn-group-vertical>.btn-group:after,.yasgui .btn-group-vertical>.btn-group:before{content:" ";display:table}.yasgui .btn-group-vertical>.btn-group:after{clear:both}.yasgui .btn-group-vertical>.btn-group>.btn{float:none}.yasgui .btn-group-vertical>.btn+.btn,.yasgui .btn-group-vertical>.btn+.btn-group,.yasgui .btn-group-vertical>.btn-group+.btn,.yasgui .btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.yasgui .btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.yasgui .btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.yasgui .btn-group-vertical>.btn:last-child:not(:first-child){border-bottom-left-radius:4px;border-top-right-radius:0;border-top-left-radius:0}.yasgui .btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.yasgui .btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.yasgui .btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.yasgui .btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.yasgui .btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.yasgui .btn-group-justified>.btn,.yasgui .btn-group-justified>.btn-group{float:none;display:table-cell;width:1%}.yasgui .btn-group-justified>.btn-group .btn{width:100%}.yasgui .btn-group-justified>.btn-group .dropdown-menu{left:auto}.yasgui [data-toggle=buttons]>.btn input[type=radio],.yasgui [data-toggle=buttons]>.btn input[type=checkbox],.yasgui [data-toggle=buttons]>.btn-group>.btn input[type=radio],.yasgui [data-toggle=buttons]>.btn-group>.btn input[type=checkbox]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.yasgui .input-group{position:relative;display:table;border-collapse:separate}.yasgui .input-group[class*=col-]{float:none;padding-left:0;padding-right:0}.yasgui .input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.yasgui .input-group .form-control,.yasgui .input-group-addon,.yasgui .input-group-btn{display:table-cell}.yasgui .input-group .form-control:not(:first-child):not(:last-child),.yasgui .input-group-addon:not(:first-child):not(:last-child),.yasgui .input-group-btn:not(:first-child):not(:last-child){border-radius:0}.yasgui .input-group-addon,.yasgui .input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.yasgui .input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.yasgui .input-group-addon.input-sm,.yasgui .input-group-sm>.input-group-addon,.yasgui .input-group-sm>.input-group-btn>.input-group-addon.btn{padding:5px 10px;font-size:12px;border-radius:3px}.yasgui .input-group-addon.input-lg,.yasgui .input-group-lg>.input-group-addon,.yasgui .input-group-lg>.input-group-btn>.input-group-addon.btn{padding:10px 16px;font-size:18px;border-radius:6px}.yasgui .input-group-addon input[type=radio],.yasgui .input-group-addon input[type=checkbox]{margin-top:0}.yasgui .input-group .form-control:first-child,.yasgui .input-group-addon:first-child,.yasgui .input-group-btn:first-child>.btn,.yasgui .input-group-btn:first-child>.btn-group>.btn,.yasgui .input-group-btn:first-child>.dropdown-toggle,.yasgui .input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.yasgui .input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.yasgui .input-group-addon:first-child{border-right:0}.yasgui .input-group .form-control:last-child,.yasgui .input-group-addon:last-child,.yasgui .input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.yasgui .input-group-btn:first-child>.btn:not(:first-child),.yasgui .input-group-btn:last-child>.btn,.yasgui .input-group-btn:last-child>.btn-group>.btn,.yasgui .input-group-btn:last-child>.dropdown-toggle{border-bottom-left-radius:0;border-top-left-radius:0}.yasgui .input-group-addon:last-child{border-left:0}.yasgui .input-group-btn{position:relative;font-size:0;white-space:nowrap}.yasgui .input-group-btn>.btn{position:relative}.yasgui .input-group-btn>.btn+.btn{margin-left:-1px}.yasgui .input-group-btn>.btn:active,.yasgui .input-group-btn>.btn:focus,.yasgui .input-group-btn>.btn:hover{z-index:2}.yasgui .input-group-btn:first-child>.btn,.yasgui .input-group-btn:first-child>.btn-group{margin-right:-1px}.yasgui .input-group-btn:last-child>.btn,.yasgui .input-group-btn:last-child>.btn-group{margin-left:-1px}.yasgui .nav{margin-bottom:0;padding-left:0;list-style:none}.yasgui .nav:after,.yasgui .nav:before{content:" ";display:table}.yasgui .nav:after{clear:both}.yasgui .nav>li{position:relative;display:block}.yasgui .nav>li>a{position:relative;display:block;padding:10px 15px}.yasgui .nav>li>a:focus,.yasgui .nav>li>a:hover{text-decoration:none;background-color:#eee}.yasgui .nav>li.disabled>a{color:#777}.yasgui .nav>li.disabled>a:focus,.yasgui .nav>li.disabled>a:hover{color:#777;text-decoration:none;background-color:transparent;cursor:not-allowed}.yasgui .nav .open>a,.yasgui .nav .open>a:focus,.yasgui .nav .open>a:hover{background-color:#eee;border-color:#337ab7}.yasgui .nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.yasgui .nav>li>a>img{max-width:none}.yasgui .nav-tabs{border-bottom:1px solid #ddd}.yasgui .nav-tabs>li{float:left;margin-bottom:-1px}.yasgui .nav-tabs>li>a{margin-right:2px;line-height:1.42857;border:1px solid transparent;border-radius:4px 4px 0 0}.yasgui .nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.yasgui .nav-tabs>li.active>a,.yasgui .nav-tabs>li.active>a:focus,.yasgui .nav-tabs>li.active>a:hover{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default}.yasgui .nav-pills>li{float:left}.yasgui .nav-pills>li>a{border-radius:4px}.yasgui .nav-pills>li+li{margin-left:2px}.yasgui .nav-pills>li.active>a,.yasgui .nav-pills>li.active>a:focus,.yasgui .nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.yasgui .nav-stacked>li{float:none}.yasgui .nav-stacked>li+li{margin-top:2px;margin-left:0}.yasgui .nav-justified,.yasgui .nav-tabs.nav-justified{width:100%}.yasgui .nav-justified>li,.yasgui .nav-tabs.nav-justified>li{float:none}.yasgui .nav-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.yasgui .nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.yasgui .nav-justified>li,.yasgui .nav-tabs.nav-justified>li{display:table-cell;width:1%}.yasgui .nav-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{margin-bottom:0}}.yasgui .nav-tabs-justified,.yasgui .nav-tabs.nav-justified{border-bottom:0}.yasgui .nav-tabs-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.yasgui .nav-tabs-justified>.active>a,.yasgui .nav-tabs-justified>.active>a:focus,.yasgui .nav-tabs-justified>.active>a:hover,.yasgui .nav-tabs.nav-justified>.active>a,.yasgui .nav-tabs.nav-justified>.active>a:focus,.yasgui .nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.yasgui .nav-tabs-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.yasgui .nav-tabs-justified>.active>a,.yasgui .nav-tabs-justified>.active>a:focus,.yasgui .nav-tabs-justified>.active>a:hover,.yasgui .nav-tabs.nav-justified>.active>a,.yasgui .nav-tabs.nav-justified>.active>a:focus,.yasgui .nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.yasgui .tab-content>.tab-pane{display:none;visibility:hidden}.yasgui .tab-content>.active{display:block;visibility:visible}.yasgui .nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.yasgui .navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}.yasgui .navbar:after,.yasgui .navbar:before{content:" ";display:table}.yasgui .navbar:after{clear:both}@media (min-width:768px){.yasgui .navbar{border-radius:4px}}.yasgui .navbar-header:after,.yasgui .navbar-header:before{content:" ";display:table}.yasgui .navbar-header:after{clear:both}@media (min-width:768px){.yasgui .navbar-header{float:left}}.yasgui .navbar-collapse{overflow-x:visible;padding-right:15px;padding-left:15px;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,.1);-webkit-overflow-scrolling:touch}.yasgui .navbar-collapse:after,.yasgui .navbar-collapse:before{content:" ";display:table}.yasgui .navbar-collapse:after{clear:both}.yasgui .navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.yasgui .navbar-collapse{width:auto;border-top:0;box-shadow:none}.yasgui .navbar-collapse.collapse{display:block!important;visibility:visible!important;height:auto!important;padding-bottom:0;overflow:visible!important}.yasgui .navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .yasgui .navbar-collapse,.navbar-fixed-top .yasgui .navbar-collapse,.navbar-static-top .yasgui .navbar-collapse{padding-left:0;padding-right:0}}.yasgui .navbar-fixed-bottom .navbar-collapse,.yasgui .navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.yasgui .navbar-fixed-bottom .navbar-collapse,.yasgui .navbar-fixed-top .navbar-collapse{max-height:200px}}.yasgui .container-fluid>.navbar-collapse,.yasgui .container-fluid>.navbar-header,.yasgui .container>.navbar-collapse,.yasgui .container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.yasgui .container-fluid>.navbar-collapse,.yasgui .container-fluid>.navbar-header,.yasgui .container>.navbar-collapse,.yasgui .container>.navbar-header{margin-right:0;margin-left:0}}.yasgui .navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.yasgui .navbar-static-top{border-radius:0}}.yasgui .navbar-fixed-bottom,.yasgui .navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.yasgui .navbar-fixed-bottom,.yasgui .navbar-fixed-top{border-radius:0}}.yasgui .navbar-fixed-top{top:0;border-width:0 0 1px}.yasgui .navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.yasgui .navbar-brand{float:left;padding:15px;font-size:18px;line-height:20px;height:50px}.yasgui .navbar-brand:focus,.yasgui .navbar-brand:hover{text-decoration:none}.yasgui .navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .yasgui .navbar-brand,.navbar>.container-fluid .yasgui .navbar-brand{margin-left:-15px}}.yasgui .navbar-toggle{position:relative;float:right;margin-right:15px;padding:9px 10px;margin-top:8px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.yasgui .navbar-toggle:focus{outline:0}.yasgui .navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.yasgui .navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.yasgui .navbar-toggle{display:none}}.yasgui .navbar-nav{margin:7.5px -15px}.yasgui .navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.yasgui .navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.yasgui .navbar-nav .open .dropdown-menu .dropdown-header,.yasgui .navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.yasgui .navbar-nav .open .dropdown-menu>li>a{line-height:20px}.yasgui .navbar-nav .open .dropdown-menu>li>a:focus,.yasgui .navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.yasgui .navbar-nav{float:left;margin:0}.yasgui .navbar-nav>li{float:left}.yasgui .navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.yasgui .navbar-form{margin:8px -15px;padding:10px 15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.yasgui .navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.yasgui .navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.yasgui .navbar-form .form-control-static{display:inline-block}.yasgui .navbar-form .input-group{display:inline-table;vertical-align:middle}.yasgui .navbar-form .input-group .form-control,.yasgui .navbar-form .input-group .input-group-addon,.yasgui .navbar-form .input-group .input-group-btn{width:auto}.yasgui .navbar-form .input-group>.form-control{width:100%}.yasgui .navbar-form .control-label{margin-bottom:0;vertical-align:middle}.yasgui .navbar-form .checkbox,.yasgui .navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.yasgui .navbar-form .checkbox label,.yasgui .navbar-form .radio label{padding-left:0}.yasgui .navbar-form .checkbox input[type=checkbox],.yasgui .navbar-form .radio input[type=radio]{position:relative;margin-left:0}.yasgui .navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.yasgui .navbar-form .form-group{margin-bottom:5px}.yasgui .navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.yasgui .navbar-form{width:auto;border:0;margin-left:0;margin-right:0;padding-top:0;padding-bottom:0;-webkit-box-shadow:none;box-shadow:none}}.yasgui .navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.yasgui .navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-radius:4px 4px 0 0}.yasgui .navbar-btn{margin-top:8px;margin-bottom:8px}.yasgui .btn-group-sm>.navbar-btn.btn,.yasgui .navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.yasgui .btn-group-xs>.navbar-btn.btn,.yasgui .navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.yasgui .navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.yasgui .navbar-text{float:left;margin-left:15px;margin-right:15px}}@media (min-width:768px){.yasgui .navbar-left{float:left!important}.yasgui .navbar-right{float:right!important;margin-right:-15px}.yasgui .navbar-right~.navbar-right{margin-right:0}}.yasgui .navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.yasgui .navbar-default .navbar-brand{color:#777}.yasgui .navbar-default .navbar-brand:focus,.yasgui .navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.yasgui .navbar-default .navbar-nav>li>a,.yasgui .navbar-default .navbar-text{color:#777}.yasgui .navbar-default .navbar-nav>li>a:focus,.yasgui .navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.yasgui .navbar-default .navbar-nav>.active>a,.yasgui .navbar-default .navbar-nav>.active>a:focus,.yasgui .navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.yasgui .navbar-default .navbar-nav>.disabled>a,.yasgui .navbar-default .navbar-nav>.disabled>a:focus,.yasgui .navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.yasgui .navbar-default .navbar-toggle{border-color:#ddd}.yasgui .navbar-default .navbar-toggle:focus,.yasgui .navbar-default .navbar-toggle:hover{background-color:#ddd}.yasgui .navbar-default .navbar-toggle .icon-bar{background-color:#888}.yasgui .navbar-default .navbar-collapse,.yasgui .navbar-default .navbar-form{border-color:#e7e7e7}.yasgui .navbar-default .navbar-nav>.open>a,.yasgui .navbar-default .navbar-nav>.open>a:focus,.yasgui .navbar-default .navbar-nav>.open>a:hover{background-color:#e7e7e7;color:#555}@media (max-width:767px){.yasgui .navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.yasgui .navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.active>a,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.yasgui .navbar-default .navbar-link{color:#777}.yasgui .navbar-default .navbar-link:hover{color:#333}.yasgui .navbar-default .btn-link{color:#777}.yasgui .navbar-default .btn-link:focus,.yasgui .navbar-default .btn-link:hover{color:#333}.yasgui .navbar-default .btn-link[disabled]:focus,.yasgui .navbar-default .btn-link[disabled]:hover,fieldset[disabled] .yasgui .navbar-default .btn-link:focus,fieldset[disabled] .yasgui .navbar-default .btn-link:hover{color:#ccc}.yasgui .navbar-inverse{background-color:#222;border-color:#090909}.yasgui .navbar-inverse .navbar-brand{color:#9d9d9d}.yasgui .navbar-inverse .navbar-brand:focus,.yasgui .navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.yasgui .navbar-inverse .navbar-nav>li>a,.yasgui .navbar-inverse .navbar-text{color:#9d9d9d}.yasgui .navbar-inverse .navbar-nav>li>a:focus,.yasgui .navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.yasgui .navbar-inverse .navbar-nav>.active>a,.yasgui .navbar-inverse .navbar-nav>.active>a:focus,.yasgui .navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#090909}.yasgui .navbar-inverse .navbar-nav>.disabled>a,.yasgui .navbar-inverse .navbar-nav>.disabled>a:focus,.yasgui .navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.yasgui .navbar-inverse .navbar-toggle{border-color:#333}.yasgui .navbar-inverse .navbar-toggle:focus,.yasgui .navbar-inverse .navbar-toggle:hover{background-color:#333}.yasgui .navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.yasgui .navbar-inverse .navbar-collapse,.yasgui .navbar-inverse .navbar-form{border-color:#101010}.yasgui .navbar-inverse .navbar-nav>.open>a,.yasgui .navbar-inverse .navbar-nav>.open>a:focus,.yasgui .navbar-inverse .navbar-nav>.open>a:hover{background-color:#090909;color:#fff}@media (max-width:767px){.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#090909}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#090909}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#090909}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.yasgui .navbar-inverse .navbar-link{color:#9d9d9d}.yasgui .navbar-inverse .navbar-link:hover{color:#fff}.yasgui .navbar-inverse .btn-link{color:#9d9d9d}.yasgui .navbar-inverse .btn-link:focus,.yasgui .navbar-inverse .btn-link:hover{color:#fff}.yasgui .navbar-inverse .btn-link[disabled]:focus,.yasgui .navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .yasgui .navbar-inverse .btn-link:focus,fieldset[disabled] .yasgui .navbar-inverse .btn-link:hover{color:#444}.yasgui .breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.yasgui .breadcrumb>li{display:inline-block}.yasgui .breadcrumb>li+li:before{content:"/\00a0";padding:0 5px;color:#ccc}.yasgui .breadcrumb>.active{color:#777}.yasgui .pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.yasgui .pagination>li{display:inline}.yasgui .pagination>li>a,.yasgui .pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.42857;text-decoration:none;color:#337ab7;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.yasgui .pagination>li:first-child>a,.yasgui .pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.yasgui .pagination>li:last-child>a,.yasgui .pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.yasgui .pagination>li>a:focus,.yasgui .pagination>li>a:hover,.yasgui .pagination>li>span:focus,.yasgui .pagination>li>span:hover{color:#23527c;background-color:#eee;border-color:#ddd}.yasgui .pagination>.active>a,.yasgui .pagination>.active>a:focus,.yasgui .pagination>.active>a:hover,.yasgui .pagination>.active>span,.yasgui .pagination>.active>span:focus,.yasgui .pagination>.active>span:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7;cursor:default}.yasgui .pagination>.disabled>a,.yasgui .pagination>.disabled>a:focus,.yasgui .pagination>.disabled>a:hover,.yasgui .pagination>.disabled>span,.yasgui .pagination>.disabled>span:focus,.yasgui .pagination>.disabled>span:hover{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.yasgui .pagination-lg>li>a,.yasgui .pagination-lg>li>span{padding:10px 16px;font-size:18px}.yasgui .pagination-lg>li:first-child>a,.yasgui .pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.yasgui .pagination-lg>li:last-child>a,.yasgui .pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.yasgui .pagination-sm>li>a,.yasgui .pagination-sm>li>span{padding:5px 10px;font-size:12px}.yasgui .pagination-sm>li:first-child>a,.yasgui .pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.yasgui .pagination-sm>li:last-child>a,.yasgui .pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.yasgui .pager{padding-left:0;margin:20px 0;list-style:none;text-align:center}.yasgui .pager:after,.yasgui .pager:before{content:" ";display:table}.yasgui .pager:after{clear:both}.yasgui .pager li{display:inline}.yasgui .pager li>a,.yasgui .pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.yasgui .pager li>a:focus,.yasgui .pager li>a:hover{text-decoration:none;background-color:#eee}.yasgui .pager .next>a,.yasgui .pager .next>span{float:right}.yasgui .pager .previous>a,.yasgui .pager .previous>span{float:left}.yasgui .pager .disabled>a,.yasgui .pager .disabled>a:focus,.yasgui .pager .disabled>a:hover,.yasgui .pager .disabled>span{color:#777;background-color:#fff;cursor:not-allowed}.yasgui .label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.yasgui .label:empty{display:none}.btn .yasgui .label{position:relative;top:-1px}.yasgui a.label:focus,.yasgui a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.yasgui .label-default{background-color:#777}.yasgui .label-default[href]:focus,.yasgui .label-default[href]:hover{background-color:#5e5e5e}.yasgui .label-primary{background-color:#337ab7}.yasgui .label-primary[href]:focus,.yasgui .label-primary[href]:hover{background-color:#286090}.yasgui .label-success{background-color:#5cb85c}.yasgui .label-success[href]:focus,.yasgui .label-success[href]:hover{background-color:#449d44}.yasgui .label-info{background-color:#5bc0de}.yasgui .label-info[href]:focus,.yasgui .label-info[href]:hover{background-color:#31b0d5}.yasgui .label-warning{background-color:#f0ad4e}.yasgui .label-warning[href]:focus,.yasgui .label-warning[href]:hover{background-color:#ec971f}.yasgui .label-danger{background-color:#d9534f}.yasgui .label-danger[href]:focus,.yasgui .label-danger[href]:hover{background-color:#c9302c}.yasgui .badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;color:#fff;line-height:1;vertical-align:baseline;white-space:nowrap;text-align:center;background-color:#777;border-radius:10px}.yasgui .badge:empty{display:none}.btn .yasgui .badge{position:relative;top:-1px}.btn-xs .yasgui .badge,.yasgui .btn-group-xs>.btn .yasgui .badge{top:0;padding:1px 5px}.list-group-item.active>.yasgui .badge,.nav-pills>.active>a>.yasgui .badge{color:#337ab7;background-color:#fff}.list-group-item>.yasgui .badge{float:right}.list-group-item>.yasgui .badge+.yasgui .badge{margin-right:5px}.nav-pills>li>a>.yasgui .badge{margin-left:3px}.yasgui a.badge:focus,.yasgui a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.yasgui .jumbotron{padding:30px 15px;margin-bottom:30px;color:inherit;background-color:#eee}.yasgui .jumbotron .h1,.yasgui .jumbotron h1{color:inherit}.yasgui .jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.yasgui .jumbotron>hr{border-top-color:#d5d5d5}.container .yasgui .jumbotron,.container-fluid .yasgui .jumbotron{border-radius:6px}.yasgui .jumbotron .container{max-width:100%}@media screen and (min-width:768px){.yasgui .jumbotron{padding:48px 0}.container .yasgui .jumbotron,.container-fluid .yasgui .jumbotron{padding-left:60px;padding-right:60px}.yasgui .jumbotron .h1,.yasgui .jumbotron h1{font-size:63px}}.yasgui .thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.yasgui .thumbnail a>img,.yasgui .thumbnail>img{display:block;max-width:100%;height:auto;margin-left:auto;margin-right:auto}.yasgui .thumbnail .caption{padding:9px;color:#333}.yasgui a.thumbnail.active,.yasgui a.thumbnail:focus,.yasgui a.thumbnail:hover{border-color:#337ab7}.yasgui .alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.yasgui .alert h4{margin-top:0;color:inherit}.yasgui .alert .alert-link{font-weight:700}.yasgui .alert>p,.yasgui .alert>ul{margin-bottom:0}.yasgui .alert>p+p{margin-top:5px}.yasgui .alert-dismissable,.yasgui .alert-dismissible{padding-right:35px}.yasgui .alert-dismissable .close,.yasgui .alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.yasgui .alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#3c763d}.yasgui .alert-success hr{border-top-color:#c9e2b3}.yasgui .alert-success .alert-link{color:#2b542c}.yasgui .alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#31708f}.yasgui .alert-info hr{border-top-color:#a6e1ec}.yasgui .alert-info .alert-link{color:#245269}.yasgui .alert-warning{background-color:#fcf8e3;border-color:#faebcc;color:#8a6d3b}.yasgui .alert-warning hr{border-top-color:#f7e1b5}.yasgui .alert-warning .alert-link{color:#66512c}.yasgui .alert-danger{background-color:#f2dede;border-color:#ebccd1;color:#a94442}.yasgui .alert-danger hr{border-top-color:#e4b9c0}.yasgui .alert-danger .alert-link{color:#843534}.yasgui .progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.yasgui .progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.yasgui .progress-bar-striped,.yasgui .progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:40px 40px}.yasgui .progress-bar.active,.yasgui .progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.yasgui .progress-bar-success{background-color:#5cb85c}.progress-striped .yasgui .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .progress-bar-info{background-color:#5bc0de}.progress-striped .yasgui .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .progress-bar-warning{background-color:#f0ad4e}.progress-striped .yasgui .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .progress-bar-danger{background-color:#d9534f}.progress-striped .yasgui .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .media{margin-top:15px}.yasgui .media:first-child{margin-top:0}.yasgui .media-right,.yasgui .media>.pull-right{padding-left:10px}.yasgui .media-left,.yasgui .media>.pull-left{padding-right:10px}.yasgui .media-body,.yasgui .media-left,.yasgui .media-right{display:table-cell;vertical-align:top}.yasgui .media-middle{vertical-align:middle}.yasgui .media-bottom{vertical-align:bottom}.yasgui .media-heading{margin-top:0;margin-bottom:5px}.yasgui .media-list{padding-left:0;list-style:none}.yasgui .list-group{margin-bottom:20px;padding-left:0}.yasgui .list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.yasgui .list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.yasgui .list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.yasgui a.list-group-item{color:#555}.yasgui a.list-group-item .list-group-item-heading{color:#333}.yasgui a.list-group-item:focus,.yasgui a.list-group-item:hover{text-decoration:none;color:#555;background-color:#f5f5f5}.yasgui .list-group-item.disabled,.yasgui .list-group-item.disabled:focus,.yasgui .list-group-item.disabled:hover{background-color:#eee;color:#777;cursor:not-allowed}.yasgui .list-group-item.disabled .list-group-item-heading,.yasgui .list-group-item.disabled:focus .list-group-item-heading,.yasgui .list-group-item.disabled:hover .list-group-item-heading{color:inherit}.yasgui .list-group-item.disabled .list-group-item-text,.yasgui .list-group-item.disabled:focus .list-group-item-text,.yasgui .list-group-item.disabled:hover .list-group-item-text{color:#777}.yasgui .list-group-item.active,.yasgui .list-group-item.active:focus,.yasgui .list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.yasgui .list-group-item.active .list-group-item-heading,.yasgui .list-group-item.active .list-group-item-heading>.small,.yasgui .list-group-item.active .list-group-item-heading>small,.yasgui .list-group-item.active:focus .list-group-item-heading,.yasgui .list-group-item.active:focus .list-group-item-heading>.small,.yasgui .list-group-item.active:focus .list-group-item-heading>small,.yasgui .list-group-item.active:hover .list-group-item-heading,.yasgui .list-group-item.active:hover .list-group-item-heading>.small,.yasgui .list-group-item.active:hover .list-group-item-heading>small{color:inherit}.yasgui .list-group-item.active .list-group-item-text,.yasgui .list-group-item.active:focus .list-group-item-text,.yasgui .list-group-item.active:hover .list-group-item-text{color:#c7ddef}.yasgui .list-group-item-success{color:#3c763d;background-color:#dff0d8}.yasgui a.list-group-item-success{color:#3c763d}.yasgui a.list-group-item-success .list-group-item-heading{color:inherit}.yasgui a.list-group-item-success:focus,.yasgui a.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}.yasgui a.list-group-item-success.active,.yasgui a.list-group-item-success.active:focus,.yasgui a.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.yasgui .list-group-item-info{color:#31708f;background-color:#d9edf7}.yasgui a.list-group-item-info{color:#31708f}.yasgui a.list-group-item-info .list-group-item-heading{color:inherit}.yasgui a.list-group-item-info:focus,.yasgui a.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}.yasgui a.list-group-item-info.active,.yasgui a.list-group-item-info.active:focus,.yasgui a.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.yasgui .list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}.yasgui a.list-group-item-warning{color:#8a6d3b}.yasgui a.list-group-item-warning .list-group-item-heading{color:inherit}.yasgui a.list-group-item-warning:focus,.yasgui a.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}.yasgui a.list-group-item-warning.active,.yasgui a.list-group-item-warning.active:focus,.yasgui a.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.yasgui .list-group-item-danger{color:#a94442;background-color:#f2dede}.yasgui a.list-group-item-danger{color:#a94442}.yasgui a.list-group-item-danger .list-group-item-heading{color:inherit}.yasgui a.list-group-item-danger:focus,.yasgui a.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}.yasgui a.list-group-item-danger.active,.yasgui a.list-group-item-danger.active:focus,.yasgui a.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.yasgui .list-group-item-heading{margin-top:0;margin-bottom:5px}.yasgui .list-group-item-text{margin-bottom:0;line-height:1.3}.yasgui .panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.yasgui .panel-body{padding:15px}.yasgui .panel-body:after,.yasgui .panel-body:before{content:" ";display:table}.yasgui .panel-body:after{clear:both}.yasgui .panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.yasgui .panel-heading>.dropdown .dropdown-toggle{color:inherit}.yasgui .panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.yasgui .panel-title>a{color:inherit}.yasgui .panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.yasgui .panel>.list-group,.yasgui .panel>.panel-collapse>.list-group{margin-bottom:0}.yasgui .panel>.list-group .list-group-item,.yasgui .panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.yasgui .panel>.list-group:first-child .list-group-item:first-child,.yasgui .panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-right-radius:3px;border-top-left-radius:3px}.yasgui .panel>.list-group:last-child .list-group-item:last-child,.yasgui .panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.yasgui .list-group+.panel-footer,.yasgui .panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.yasgui .panel>.panel-collapse>.table,.yasgui .panel>.table,.yasgui .panel>.table-responsive>.table{margin-bottom:0}.yasgui .panel>.panel-collapse>.table caption,.yasgui .panel>.table caption,.yasgui .panel>.table-responsive>.table caption{padding-left:15px;padding-right:15px}.yasgui .panel>.table-responsive:first-child>.table:first-child,.yasgui .panel>.table:first-child{border-top-right-radius:3px;border-top-left-radius:3px}.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child,.yasgui .panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-left-radius:3px;border-bottom-right-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.yasgui .panel>.panel-body+.table,.yasgui .panel>.panel-body+.table-responsive,.yasgui .panel>.table+.panel-body,.yasgui .panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.yasgui .panel>.table>tbody:first-child>tr:first-child td,.yasgui .panel>.table>tbody:first-child>tr:first-child th{border-top:0}.yasgui .panel>.table-bordered,.yasgui .panel>.table-responsive>.table-bordered{border:0}.yasgui .panel>.table-bordered>tbody>tr>td:first-child,.yasgui .panel>.table-bordered>tbody>tr>th:first-child,.yasgui .panel>.table-bordered>tfoot>tr>td:first-child,.yasgui .panel>.table-bordered>tfoot>tr>th:first-child,.yasgui .panel>.table-bordered>thead>tr>td:first-child,.yasgui .panel>.table-bordered>thead>tr>th:first-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.yasgui .panel>.table-bordered>tbody>tr>td:last-child,.yasgui .panel>.table-bordered>tbody>tr>th:last-child,.yasgui .panel>.table-bordered>tfoot>tr>td:last-child,.yasgui .panel>.table-bordered>tfoot>tr>th:last-child,.yasgui .panel>.table-bordered>thead>tr>td:last-child,.yasgui .panel>.table-bordered>thead>tr>th:last-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.yasgui .panel>.table-bordered>tbody>tr:first-child>td,.yasgui .panel>.table-bordered>tbody>tr:first-child>th,.yasgui .panel>.table-bordered>tbody>tr:last-child>td,.yasgui .panel>.table-bordered>tbody>tr:last-child>th,.yasgui .panel>.table-bordered>tfoot>tr:last-child>td,.yasgui .panel>.table-bordered>tfoot>tr:last-child>th,.yasgui .panel>.table-bordered>thead>tr:first-child>td,.yasgui .panel>.table-bordered>thead>tr:first-child>th,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th,.yasgui .panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.yasgui .panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.yasgui .panel>.table-responsive{border:0;margin-bottom:0}.yasgui .panel-group{margin-bottom:20px}.yasgui .panel-group .panel{margin-bottom:0;border-radius:4px}.yasgui .panel-group .panel+.panel{margin-top:5px}.yasgui .panel-group .panel-heading{border-bottom:0}.yasgui .panel-group .panel-heading+.panel-collapse>.list-group,.yasgui .panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.yasgui .panel-group .panel-footer{border-top:0}.yasgui .panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.yasgui .panel-default{border-color:#ddd}.yasgui .panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.yasgui .panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.yasgui .panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.yasgui .panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.yasgui .panel-primary{border-color:#337ab7}.yasgui .panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.yasgui .panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.yasgui .panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.yasgui .panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.yasgui .panel-success{border-color:#d6e9c6}.yasgui .panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.yasgui .panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.yasgui .panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.yasgui .panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.yasgui .panel-info{border-color:#bce8f1}.yasgui .panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.yasgui .panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.yasgui .panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.yasgui .panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.yasgui .panel-warning{border-color:#faebcc}.yasgui .panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.yasgui .panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.yasgui .panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.yasgui .panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.yasgui .panel-danger{border-color:#ebccd1}.yasgui .panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.yasgui .panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.yasgui .panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.yasgui .panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.yasgui .embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.yasgui .embed-responsive .embed-responsive-item,.yasgui .embed-responsive embed,.yasgui .embed-responsive iframe,.yasgui .embed-responsive object,.yasgui .embed-responsive video{position:absolute;top:0;left:0;bottom:0;height:100%;width:100%;border:0}.yasgui .embed-responsive.embed-responsive-16by9{padding-bottom:56.25%}.yasgui .embed-responsive.embed-responsive-4by3{padding-bottom:75%}.yasgui .well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.yasgui .well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.yasgui .well-lg{padding:24px;border-radius:6px}.yasgui .well-sm{padding:9px;border-radius:3px}.yasgui .close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.yasgui .close:focus,.yasgui .close:hover{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}.yasgui button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.yasgui .modal-open{overflow:hidden}.yasgui .modal{display:none;overflow:hidden;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;-webkit-overflow-scrolling:touch;outline:0}.yasgui .modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.yasgui .modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.yasgui .modal-open .modal{overflow-x:hidden;overflow-y:auto}.yasgui .modal-dialog{position:relative;width:auto;margin:10px}.yasgui .modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.yasgui .modal-backdrop{position:absolute;top:0;right:0;left:0;background-color:#000}.yasgui .modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.yasgui .modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.yasgui .modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.43px}.yasgui .modal-header .close{margin-top:-2px}.yasgui .modal-title{margin:0;line-height:1.42857}.yasgui .modal-body{position:relative;padding:15px}.yasgui .modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.yasgui .modal-footer:after,.yasgui .modal-footer:before{content:" ";display:table}.yasgui .modal-footer:after{clear:both}.yasgui .modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.yasgui .modal-footer .btn-group .btn+.btn{margin-left:-1px}.yasgui .modal-footer .btn-block+.btn-block{margin-left:0}.yasgui .modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.yasgui .modal-dialog{width:600px;margin:30px auto}.yasgui .modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.yasgui .modal-sm{width:300px}}@media (min-width:992px){.yasgui .modal-lg{width:900px}}.yasgui .tooltip{position:absolute;z-index:1070;display:block;visibility:visible;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-weight:400;line-height:1.4;opacity:0;filter:alpha(opacity=0)}.yasgui .tooltip.in{opacity:.9;filter:alpha(opacity=90)}.yasgui .tooltip.top{margin-top:-3px;padding:5px 0}.yasgui .tooltip.right{margin-left:3px;padding:0 5px}.yasgui .tooltip.bottom{margin-top:3px;padding:5px 0}.yasgui .tooltip.left{margin-left:-3px;padding:0 5px}.yasgui .tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.yasgui .tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.yasgui .tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.yasgui .tooltip.top-left .tooltip-arrow{bottom:0;right:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.yasgui .tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.yasgui .tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.yasgui .tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.yasgui .tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.yasgui .tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.yasgui .tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.yasgui .popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;line-height:1.42857;text-align:left;background-color:#fff;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);white-space:normal}.yasgui .popover.top{margin-top:-10px}.yasgui .popover.right{margin-left:10px}.yasgui .popover.bottom{margin-top:10px}.yasgui .popover.left{margin-left:-10px}.yasgui .popover-title{margin:0;padding:8px 14px;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.yasgui .popover-content{padding:9px 14px}.yasgui .popover>.arrow,.yasgui .popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.yasgui .popover>.arrow{border-width:11px}.yasgui .popover>.arrow:after{border-width:10px;content:""}.yasgui .popover.top>.arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px}.yasgui .popover.top>.arrow:after{content:" ";bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#fff}.yasgui .popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25)}.yasgui .popover.right>.arrow:after{content:" ";left:1px;bottom:-10px;border-left-width:0;border-right-color:#fff}.yasgui .popover.bottom>.arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);top:-11px}.yasgui .popover.bottom>.arrow:after{content:" ";top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.yasgui .popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.yasgui .popover.left>.arrow:after{content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-10px}.yasgui .carousel{position:relative}.yasgui .carousel-inner{position:relative;overflow:hidden;width:100%}.yasgui .carousel-inner>.item{display:none;position:relative;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.yasgui .carousel-inner>.item>a>img,.yasgui .carousel-inner>.item>img{display:block;max-width:100%;height:auto;line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.yasgui .carousel-inner>.item{transition:transform .6s ease-in-out;backface-visibility:hidden;perspective:1000}.yasgui .carousel-inner>.item.active.right,.yasgui .carousel-inner>.item.next{transform:translate3d(100%,0,0);left:0}.yasgui .carousel-inner>.item.active.left,.yasgui .carousel-inner>.item.prev{transform:translate3d(-100%,0,0);left:0}.yasgui .carousel-inner>.item.active,.yasgui .carousel-inner>.item.next.left,.yasgui .carousel-inner>.item.prev.right{transform:translate3d(0,0,0);left:0}}.yasgui .carousel-inner>.active,.yasgui .carousel-inner>.next,.yasgui .carousel-inner>.prev{display:block}.yasgui .carousel-inner>.active{left:0}.yasgui .carousel-inner>.next,.yasgui .carousel-inner>.prev{position:absolute;top:0;width:100%}.yasgui .carousel-inner>.next{left:100%}.yasgui .carousel-inner>.prev{left:-100%}.yasgui .carousel-inner>.next.left,.yasgui .carousel-inner>.prev.right{left:0}.yasgui .carousel-inner>.active.left{left:-100%}.yasgui .carousel-inner>.active.right{left:100%}.yasgui .carousel-control{position:absolute;top:0;left:0;bottom:0;width:15%;opacity:.5;filter:alpha(opacity=50);font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.yasgui .carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1)}.yasgui .carousel-control.right{left:auto;right:0;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1)}.yasgui .carousel-control:focus,.yasgui .carousel-control:hover{outline:0;color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next,.yasgui .carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block}.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .icon-prev{left:50%;margin-left:-10px}.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next{right:50%;margin-right:-10px}.yasgui .carousel-control .icon-next,.yasgui .carousel-control .icon-prev{width:20px;height:20px;margin-top:-10px;font-family:serif}.yasgui .carousel-control .icon-prev:before{content:'\2039'}.yasgui .carousel-control .icon-next:before{content:'\203a'}.yasgui .carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;margin-left:-30%;padding-left:0;list-style:none;text-align:center}.yasgui .carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;border:1px solid #fff;border-radius:10px;cursor:pointer;background-color:transparent}.yasgui .carousel-indicators .active{margin:0;width:12px;height:12px;background-color:#fff}.yasgui .carousel-caption{position:absolute;left:15%;right:15%;bottom:20px;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.yasgui .carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next,.yasgui .carousel-control .icon-prev{width:30px;height:30px;margin-top:-15px;font-size:30px}.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .icon-prev{margin-left:-15px}.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next{margin-right:-15px}.yasgui .carousel-caption{left:20%;right:20%;padding-bottom:30px}.yasgui .carousel-indicators{bottom:20px}}.yasgui .clearfix:after,.yasgui .clearfix:before{content:" ";display:table}.yasgui .clearfix:after{clear:both}.yasgui .center-block{display:block;margin-left:auto;margin-right:auto}.yasgui .pull-right{float:right!important}.yasgui .pull-left{float:left!important}.yasgui .hide{display:none!important}.yasgui .show{display:block!important}.yasgui .invisible{visibility:hidden}.yasgui .text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.yasgui .hidden{display:none!important;visibility:hidden!important}.yasgui .affix{position:fixed}.yasgui .visible-lg,.yasgui .visible-lg-block,.yasgui .visible-lg-inline,.yasgui .visible-lg-inline-block,.yasgui .visible-md,.yasgui .visible-md-block,.yasgui .visible-md-inline,.yasgui .visible-md-inline-block,.yasgui .visible-print,.yasgui .visible-print-block,.yasgui .visible-print-inline,.yasgui .visible-print-inline-block,.yasgui .visible-sm,.yasgui .visible-sm-block,.yasgui .visible-sm-inline,.yasgui .visible-sm-inline-block,.yasgui .visible-xs,.yasgui .visible-xs-block,.yasgui .visible-xs-inline,.yasgui .visible-xs-inline-block{display:none!important}@media (max-width:767px){.yasgui .visible-xs{display:block!important}.yasgui table.visible-xs{display:table}.yasgui tr.visible-xs{display:table-row!important}.yasgui td.visible-xs,.yasgui th.visible-xs{display:table-cell!important}}@media (max-width:767px){.yasgui .visible-xs-block{display:block!important}}@media (max-width:767px){.yasgui .visible-xs-inline{display:inline!important}}@media (max-width:767px){.yasgui .visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm{display:block!important}.yasgui table.visible-sm{display:table}.yasgui tr.visible-sm{display:table-row!important}.yasgui td.visible-sm,.yasgui th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md{display:block!important}.yasgui table.visible-md{display:table}.yasgui tr.visible-md{display:table-row!important}.yasgui td.visible-md,.yasgui th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.yasgui .visible-lg{display:block!important}.yasgui table.visible-lg{display:table}.yasgui tr.visible-lg{display:table-row!important}.yasgui td.visible-lg,.yasgui th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.yasgui .visible-lg-block{display:block!important}}@media (min-width:1200px){.yasgui .visible-lg-inline{display:inline!important}}@media (min-width:1200px){.yasgui .visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.yasgui .hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.yasgui .hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .hidden-md{display:none!important}}@media (min-width:1200px){.yasgui .hidden-lg{display:none!important}}@media print{.yasgui .visible-print{display:block!important}.yasgui table.visible-print{display:table}.yasgui tr.visible-print{display:table-row!important}.yasgui td.visible-print,.yasgui th.visible-print{display:table-cell!important}}@media print{.yasgui .visible-print-block{display:block!important}}@media print{.yasgui .visible-print-inline{display:inline!important}}@media print{.yasgui .visible-print-inline-block{display:inline-block!important}}@media print{.yasgui .hidden-print{display:none!important}}.yasgui .yasqe .CodeMirror,.yasgui .yasr .CodeMirror{border-color:#ddd}.yasgui .nav-tabs li.tab-sortable-highlight{border:3px dashed #ddd;border-bottom:0}.yasgui .nav-tabs li a[role=addTab]{padding:0;margin:4px 0;cursor:pointer;font-weight:700;font-size:21px;background-color:transparent;border-color:transparent}.yasgui .nav-tabs li .close{margin-left:7px;font-size:17px}.yasgui .nav-tabs li a{display:inline-block}.yasgui .nav-tabs li div{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default;padding:10px 15px;display:none}.yasgui .nav-tabs li.rename a{display:none}.yasgui .nav-tabs li.rename div{display:inline-block}.yasgui .menu-slide{position:absolute;border:1px solid #ddd;border-top:0;top:0;left:0;z-index:100;visibility:hidden;width:600px;height:auto;background:#f5f5f5;-webkit-transition:all .5s;transition:all .5s;-webkit-perspective:1500px;perspective:1500px;-webkit-perspective-origin:0 50%;perspective-origin:0 50%;-webkit-transform:translate3d(-100%,0,0) rotateY(90deg);transform:translate3d(-100%,0,0) rotateY(90deg);-webkit-transform-origin:100% 50%;transform-origin:100% 50%;-webkit-transform-style:preserve-3d;transform-style:preserve-3d}.yasgui .menu-slide .yasguiLogo{cursor:pointer;float:right;margin:5px;height:100px;width:100px}.yasgui .menu-slide::after{display:none}.yasgui .menu-slide .tab-pane,.yasgui .menu-slide .tabPaneMenuTabs{margin:10px}.yasgui .menu-slide .logo{margin-left:auto;margin-right:0}.yasgui .menu-slide .requestConfig .textInputsRow:first-child .close{display:none}.yasgui .menu-slide .requestConfig .close{font-size:18px}.yasgui .menu-slide .requestConfig .textInputsRow *{margin:5px 3px 0 0}.yasgui .menu-slide .requestConfig .row{display:table;margin:5px 0}.yasgui .menu-slide .requestConfig label{font-size:80%}.yasgui .menu-slide .requestConfig .rowLabel{font-weight:700}.yasgui .menu-slide .requestConfig [class*=col-]{float:none;display:table-cell;vertical-align:middle;padding:5px}.yasgui .tab-pane.menu-open{-webkit-perspective:1500px;perspective:1500px;-webkit-perspective-origin:0 50%;perspective-origin:0 50%}.yasgui .wrapper{position:relative;left:0;z-index:99;height:100%;-webkit-transition:-webkit-transform .5s;transition:transform .5s}.yasgui .menu-open .menu-slide{left:600px;visibility:visible;-webkit-transition:all .5s;-moz-transition:all .5s;-ms-transition:all .5s;-o-transition:all .5s;transition:all .5s;-webkit-transform:translate3d(-100%,0,0) rotateY(0deg);transform:translate3d(-100%,0,0) rotateY(0deg)}.yasgui .controlbar{position:relative;left:0;-webkit-transition:all .5s;-moz-transition:all .5s;-ms-transition:all .5s;-o-transition:all .5s;transition:all .5s;padding:5px 5px 0;border-left:1px solid #ddd}.yasgui .controlbar .endpointText{width:400px}.yasgui .controlbar .endpointText .endpointOptionRow{vertical-align:middle}.yasgui .controlbar .endpointText .endpointOptionRow:hover{background-color:#e6e6e6}.yasgui .controlbar .endpointText .endpointOptionRow .close{display:table-cell;vertical-align:middle}.yasgui .controlbar .endpointText .endpointOptionRow .endpointUrl{font-weight:700;font-size:.9;width:95%;-ms-word-break:break-all;word-break:break-all;word-break:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;-ms-hyphens:auto;hyphens:auto}.yasgui .controlbar .endpointText .endpointOptionRow .endpointTitle{font-size:12px;opacity:.5}.yasgui .controlbar>*{vertical-align:top;margin-right:5px;display:inline-block}.yasgui .controlbar .menuButton{display:inline-block;vertical-align:middle;padding-left:10px;padding-right:10px;height:34px}.yasgui .controlbar .menuButton:focus{outline:0;background-color:transparent;border-color:#ccc}.yasgui .controlbar .menuButton .icon-bar{margin-bottom:3px;display:block;width:20px;height:3px;background-color:#777;border-radius:1px}.yasgui .menu-open .controlbar{border-left:0;left:600px}.yasgui .selectize-control.plugin-remove_button .disabled [data-value] .remove{border-left-color:#fff}.yasgui .selectize-control.multi .selectize-input.disabled>div,.yasgui .selectize-control.multi .selectize-input.disabled>div.active{border:0 solid #fff}.yasgui .selectize-control.plugin-drag_drop.multi>.selectize-input>div.ui-sortable-placeholder{visibility:visible!important;background:#f2f2f2!important;background:rgba(0,0,0,.06)!important;border:0!important;-webkit-box-shadow:inset 0 0 12px 4px #fff;box-shadow:inset 0 0 12px 4px #fff}.yasgui .selectize-control.plugin-drag_drop .ui-sortable-placeholder::after{content:'!';visibility:hidden}.yasgui .selectize-control.plugin-drag_drop .ui-sortable-helper{-webkit-box-shadow:0 2px 5px rgba(0,0,0,.2);box-shadow:0 2px 5px rgba(0,0,0,.2)}.yasgui .selectize-dropdown-header{position:relative;border-bottom:1px solid #d0d0d0;background:#f8f8f8;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.yasgui .selectize-dropdown-header-close{position:absolute;right:12px;top:50%;color:#333;opacity:.4;margin-top:-12px;line-height:20px;font-size:20px!important}.yasgui .selectize-dropdown-header-close:hover{color:#000}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup{border-right:1px solid #f2f2f2;border-top:0 none;float:left;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup:last-child{border-right:0 none}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup:before{display:none}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup-header{border-top:0 none}.yasgui .selectize-control.plugin-remove_button [data-value]{position:relative;padding-right:24px!important}.yasgui .selectize-control.plugin-remove_button [data-value] .remove{z-index:1;position:absolute;top:0;right:0;bottom:0;width:17px;text-align:center;font-weight:700;font-size:12px;color:inherit;text-decoration:none;vertical-align:middle;display:inline-block;padding:1px 0 0;border-left:1px solid transparent;-webkit-border-radius:0 2px 2px 0;-moz-border-radius:0 2px 2px 0;border-radius:0 2px 2px 0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui .selectize-control.plugin-remove_button [data-value] .remove:hover{background:rgba(0,0,0,.05)}.yasgui .selectize-control.plugin-remove_button [data-value].active .remove{border-left-color:transparent}.yasgui .selectize-control.plugin-remove_button .disabled [data-value] .remove:hover{background:0 0}.yasgui .selectize-control.plugin-remove_button .disabled [data-value] .remove{border-left-color:rgba(77,77,77,0)}.yasgui .selectize-control{position:relative}.yasgui .selectize-dropdown,.yasgui .selectize-input,.yasgui .selectize-input input{color:#333;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;-webkit-font-smoothing:inherit}.yasgui .selectize-control.single .selectize-input.input-active,.yasgui .selectize-input{background:#fff;display:inline-block}.yasgui .selectize-input{border:1px solid #ccc;padding:6px 12px;display:inline-block;width:100%;overflow:hidden;position:relative;z-index:1;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-box-shadow:none;box-shadow:none;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.yasgui .selectize-control.multi .selectize-input.has-items{padding:5px 12px 2px}.yasgui .selectize-input.full{background-color:#fff}.yasgui .selectize-input.disabled,.yasgui .selectize-input.disabled *{cursor:default!important}.yasgui .selectize-input>*{vertical-align:baseline;display:-moz-inline-stack;display:inline-block;zoom:1}.yasgui .selectize-control.multi .selectize-input>div{cursor:pointer;margin:0 3px 3px 0;padding:1px 3px;background:#efefef;color:#333;border:0 solid transparent}.yasgui .selectize-control.multi .selectize-input>div.active{background:#428bca;color:#fff;border:0 solid transparent}.yasgui .selectize-control.multi .selectize-input.disabled>div,.yasgui .selectize-control.multi .selectize-input.disabled>div.active{color:grey;background:#fff;border:0 solid rgba(77,77,77,0)}.yasgui .selectize-input>input{display:inline-block!important;padding:0!important;min-height:0!important;max-height:none!important;max-width:100%!important;margin:0!important;text-indent:0!important;border:0!important;background:0 0!important;line-height:inherit!important;-webkit-user-select:auto!important;-webkit-box-shadow:none!important;box-shadow:none!important}.yasgui .selectize-input>input::-ms-clear{display:none}.yasgui .selectize-input>input:focus{outline:0!important}.yasgui .selectize-input::after{content:' ';display:block;clear:left}.yasgui .selectize-input.dropdown-active::before{content:' ';position:absolute;background:#fff;height:1px;bottom:0;left:0;right:0}.yasgui .selectize-dropdown{position:absolute;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui .selectize-dropdown [data-selectable]{cursor:pointer;overflow:hidden}.yasgui .selectize-dropdown [data-selectable] .highlight{background:rgba(255,237,40,.4);-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px}.yasgui .selectize-dropdown .optgroup-header,.yasgui .selectize-dropdown [data-selectable]{padding:3px 12px}.yasgui .selectize-dropdown .optgroup:first-child .optgroup-header{border-top:0 none}.yasgui .selectize-dropdown .optgroup-header{color:#777;background:#fff;cursor:default}.yasgui .selectize-dropdown .active{background-color:#f5f5f5;color:#262626}.yasgui .selectize-dropdown .active.create{color:#262626}.yasgui .selectize-dropdown .create{color:rgba(51,51,51,.5)}.yasgui .selectize-dropdown-content{overflow-y:auto;overflow-x:hidden;max-height:200px}.yasgui .selectize-control.single .selectize-input,.yasgui .selectize-control.single .selectize-input input{cursor:pointer}.yasgui .selectize-control.single .selectize-input.input-active,.yasgui .selectize-control.single .selectize-input.input-active input{cursor:text}.yasgui .selectize-control.single .selectize-input:after{content:' ';display:block;position:absolute;top:50%;right:17px;margin-top:-3px;width:0;height:0;border-style:solid;border-width:5px 5px 0;border-color:#333 transparent transparent}.yasgui .selectize-control.single .selectize-input.dropdown-active:after{margin-top:-4px;border-width:0 5px 5px;border-color:transparent transparent #333}.yasgui .selectize-control.rtl.single .selectize-input:after{left:17px;right:auto}.yasgui .selectize-control.rtl .selectize-input>input{margin:0 4px 0 -2px!important}.yasgui .selectize-control .selectize-input.disabled{opacity:.5;background-color:#fff}.yasgui .selectize-dropdown,.yasgui .selectize-dropdown.form-control{height:auto;padding:0;margin:2px 0 0;z-index:1000;background:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.yasgui .selectize-dropdown .optgroup-header{font-size:12px;line-height:1.42857}.yasgui .selectize-dropdown .optgroup:first-child:before{display:none}.yasgui .selectize-dropdown .optgroup:before{content:' ';display:block;height:1px;margin:9px -12px;overflow:hidden;background-color:#e5e5e5}.yasgui .selectize-dropdown-content{padding:5px 0}.yasgui .selectize-dropdown-header{padding:6px 12px}.yasgui .selectize-input{min-height:34px}.yasgui .selectize-input.dropdown-active{-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.yasgui .selectize-input.dropdown-active::before{display:none}.yasgui .selectize-input.focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.yasgui .has-error .selectize-input{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-error .selectize-input:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.yasgui .selectize-control.multi .selectize-input.has-items{padding-left:9px;padding-right:9px}.yasgui .selectize-control.multi .selectize-input>div{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.yasgui .form-control.selectize-control{padding:0;height:auto;border:none;background:0 0;-webkit-box-shadow:none;box-shadow:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.yasqe{@-moz-keyframes blink { 0% { background:#7e7}@-webkit-keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}@keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}.yasqe .CodeMirror{font-family:monospace;height:300px}.yasqe .CodeMirror-scroll{overflow:auto}.yasqe .CodeMirror-lines{padding:4px 0}.yasqe .CodeMirror pre{padding:0 4px}.yasqe .CodeMirror-gutter-filler,.yasqe .CodeMirror-scrollbar-filler{background-color:#fff}.yasqe .CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.yasqe .CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;-moz-box-sizing:content-box;box-sizing:content-box}.yasqe .CodeMirror-guttermarker{color:#000}.yasqe .CodeMirror-guttermarker-subtle{color:#999}.yasqe .CodeMirror div.CodeMirror-cursor{border-left:1px solid #000}.yasqe .CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.yasqe .CodeMirror.cm-fat-cursor div.CodeMirror-cursor{width:auto;border:0;background:#7e7}.yasqe .CodeMirror.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.yasqe .cm-animate-fat-cursor{width:auto;border:0;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.yasqe .cm-tab{display:inline-block;text-decoration:inherit}.yasqe .CodeMirror-ruler{border-left:1px solid #ccc;position:absolute}.yasqe .cm-s-default .cm-keyword{color:#708}.yasqe .cm-s-default .cm-atom{color:#219}.yasqe .cm-s-default .cm-number{color:#164}.yasqe .cm-s-default .cm-def{color:#00f}.yasqe .cm-s-default .cm-variable-2{color:#05a}.yasqe .cm-s-default .cm-variable-3{color:#085}.yasqe .cm-s-default .cm-comment{color:#a50}.yasqe .cm-s-default .cm-string{color:#a11}.yasqe .cm-s-default .cm-string-2{color:#f50}.yasqe .cm-s-default .cm-meta,.yasqe .cm-s-default .cm-qualifier{color:#555}.yasqe .cm-s-default .cm-builtin{color:#30a}.yasqe .cm-s-default .cm-bracket{color:#997}.yasqe .cm-s-default .cm-tag{color:#170}.yasqe .cm-s-default .cm-attribute{color:#00c}.yasqe .cm-s-default .cm-header{color:#00f}.yasqe .cm-s-default .cm-quote{color:#090}.yasqe .cm-s-default .cm-hr{color:#999}.yasqe .cm-s-default .cm-link{color:#00c}.yasqe .cm-negative{color:#d44}.yasqe .cm-positive{color:#292}.yasqe .cm-header,.yasqe .cm-strong{font-weight:700}.yasqe .cm-em{font-style:italic}.yasqe .cm-link{text-decoration:underline}.yasqe .cm-strikethrough{text-decoration:line-through}.yasqe .cm-invalidchar,.yasqe .cm-s-default .cm-error{color:red}.yasqe div.CodeMirror span.CodeMirror-matchingbracket{color:#0f0}.yasqe div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#f22}.yasqe .CodeMirror-matchingtag{background:rgba(255,150,0,.3)}.yasqe .CodeMirror-activeline-background{background:#e8f2ff}.yasqe .CodeMirror{position:relative;overflow:hidden;background:#fff;color:#000}.yasqe .CodeMirror-scroll{margin-bottom:-30px;margin-right:-30px;padding-bottom:30px;height:100%;outline:0;position:relative;-moz-box-sizing:content-box;box-sizing:content-box}.yasqe .CodeMirror-sizer{position:relative;border-right:30px solid transparent;-moz-box-sizing:content-box;box-sizing:content-box}.yasqe .CodeMirror-gutter-filler,.yasqe .CodeMirror-hscrollbar,.yasqe .CodeMirror-scrollbar-filler,.yasqe .CodeMirror-vscrollbar{position:absolute;z-index:6;display:none}.yasqe .CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.yasqe .CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.yasqe .CodeMirror-scrollbar-filler{right:0;bottom:0}.yasqe .CodeMirror-gutter-filler{left:0;bottom:0}.yasqe .CodeMirror-gutters{position:absolute;left:0;top:0;padding-bottom:30px;z-index:3}.yasqe .CodeMirror-gutter{white-space:normal;height:100%;-moz-box-sizing:content-box;box-sizing:content-box;padding-bottom:30px;margin-bottom:-32px;display:inline-block}.yasqe .CodeMirror-gutter-wrapper{position:absolute;z-index:4;height:100%}.yasqe .CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.yasqe .CodeMirror-lines{cursor:text;min-height:1px}.yasqe .CodeMirror pre{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:0 0;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible}.yasqe .CodeMirror-wrap pre{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.yasqe .CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.yasqe .CodeMirror-linewidget{position:relative;z-index:2;overflow:auto}.yasqe .CodeMirror-wrap .CodeMirror-scroll{overflow-x:hidden}.yasqe .CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.yasqe .CodeMirror-measure pre{position:static}.yasqe .CodeMirror div.CodeMirror-cursor{position:absolute;border-right:none;width:0}.yasqe div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}.yasqe .CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.yasqe .CodeMirror-selected{background:#d9d9d9}.yasqe .CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.yasqe .CodeMirror-crosshair{cursor:crosshair}.yasqe .cm-searching{background:#ffa;background:rgba(255,255,0,.4)}.yasqe .cm-force-border{padding-right:.1px}@media print{.yasqe .CodeMirror div.CodeMirror-cursors{visibility:hidden}}.yasqe .cm-tab-wrap-hack:after{content:''}.yasqe span.CodeMirror-selectedtext{background:0 0}.yasqe .CodeMirror-fullscreen{position:fixed;top:0;left:0;right:0;bottom:0;height:auto;z-index:9}.yasqe .CodeMirror-foldmarker{color:#00f;text-shadow:#b9f 1px 1px 2px,#b9f -1px -1px 2px,#b9f 1px -1px 2px,#b9f -1px 1px 2px;font-family:arial;line-height:.3;cursor:pointer}.yasqe .CodeMirror-foldgutter{width:.7em}.yasqe .CodeMirror-foldgutter-folded,.yasqe .CodeMirror-foldgutter-open{cursor:pointer}.yasqe .CodeMirror-foldgutter-open:after{content:"\25BE"}.yasqe .CodeMirror-foldgutter-folded:after{content:"\25B8"}.yasqe .svgImg{display:inline-block}.yasqe .CodeMirror{line-height:1.5em;border:1px solid #d1d1d1}.yasqe pre{font-size:13px}.yasqe span.cm-error{border-bottom:2px dotted red}.yasqe .gutterErrorBar{width:4px}.yasqe .yasqe_buttons{position:absolute;top:5px;right:5px;z-index:5}.yasqe .yasqe_buttons div{vertical-align:top;margin-left:5px}.yasqe .yasqe_queryButton{display:inline-block;cursor:pointer;width:40px;height:40px}.yasqe .yasqe_queryButton .svgImg{display:block}.yasqe .yasqe_share{cursor:pointer;height:20px;width:20px;margin-top:3px}.yasqe .yasqe_sharePopup{position:absolute;padding:6px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05);width:400px;height:auto}.yasqe .yasqe_sharePopup textarea{width:100%}.yasqe .completionNotification{color:#999;background-color:#f7f7f7;position:absolute;padding:0 5px;right:0;bottom:0;font-size:90%}.yasqe .CodeMirror-fullscreen .fullscreenToggleBtns .yasqe_smallscreenBtn{display:inline-block}.yasqe .CodeMirror-fullscreen .fullscreenToggleBtns .yasqe_fullscreenBtn{display:none}.yasqe .fullscreenToggleBtns{display:inline-block;margin-top:3px}.yasqe .fullscreenToggleBtns div{cursor:pointer;width:20px;height:20px}.yasqe .fullscreenToggleBtns .yasqe_smallscreenBtn{display:none}.yasqe .parseErrorIcon{width:15px;height:15px}.yasqe .yasqe_tooltip{display:inline;background:#333;background:rgba(0,0,0,.8);border-radius:5px;bottom:26px;color:#fff;left:20%;padding:5px 15px;position:absolute;width:220px;white-space:-moz-pre-wrap!important;white-space:-pre-wrap;white-space:-o-pre-wrap;white-space:pre-wrap;white-space:normal}.yasqe .notificationLoader{width:18px;height:18px;vertical-align:middle}.CodeMirror-hints{position:absolute;z-index:10;overflow:hidden;list-style:none;margin:0;padding:2px;-webkit-box-shadow:2px 3px 5px rgba(0,0,0,.2);-moz-box-shadow:2px 3px 5px rgba(0,0,0,.2);box-shadow:2px 3px 5px rgba(0,0,0,.2);border-radius:3px;border:1px solid silver;background:#fff;font-size:90%;font-family:monospace;max-height:20em;overflow-y:auto}.CodeMirror-hint{margin:0;padding:0 4px;border-radius:2px;overflow:hidden;white-space:pre;color:#000;cursor:pointer}li.CodeMirror-hint-active{background:#08f;color:#fff}.CodeMirror-hint{max-width:30em}.yasr{padding-top:5px;background-color:#fff;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857;color:#333;@-moz-keyframes blink { 0% { background:#7e7}50%{background:0 0}100%{background:#7e7}@-webkit-keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}@keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}.yasr .svgImg{display:inline-block;bottom:-2px}.yasr button.btn_smallscreen{display:none}.yasr button.btn_fullscreen div,.yasr button.btn_smallscreen div{width:15px;height:15px}.yasr.yasr_fullscreen{z-index:10;position:fixed;top:0;bottom:0;left:0;right:0}.yasr.yasr_fullscreen .btn_smallscreen{display:inline-block}.yasr.yasr_fullscreen .btn_fullscreen{display:none}.yasr table.dataTable{width:100%;margin:0 auto;clear:both;border-collapse:separate;border-spacing:0}.yasr table.dataTable tfoot th,.yasr table.dataTable thead th{font-weight:700}.yasr table.dataTable thead td,.yasr table.dataTable thead th{padding:10px 18px;border-bottom:1px solid #111}.yasr table.dataTable thead td:active,.yasr table.dataTable thead th:active{outline:0}.yasr table.dataTable tfoot td,.yasr table.dataTable tfoot th{padding:10px 18px 6px;border-top:1px solid #111}.yasr table.dataTable thead .sorting,.yasr table.dataTable thead .sorting_asc,.yasr table.dataTable thead .sorting_desc{cursor:pointer}.yasr table.dataTable thead .sorting{background:url(../images/sort_both.png) center right no-repeat}.yasr table.dataTable thead .sorting_asc{background:url(../images/sort_asc.png) center right no-repeat}.yasr table.dataTable thead .sorting_desc{background:url(../images/sort_desc.png) center right no-repeat}.yasr table.dataTable thead .sorting_asc_disabled{background:url(../images/sort_asc_disabled.png) center right no-repeat}.yasr table.dataTable thead .sorting_desc_disabled{background:url(../images/sort_desc_disabled.png) center right no-repeat}.yasr table.dataTable tbody tr{background-color:#fff}.yasr table.dataTable tbody tr.selected{background-color:#b0bed9}.yasr table.dataTable tbody td,.yasr table.dataTable tbody th{padding:8px 10px}.yasr table.dataTable.display tbody td,.yasr table.dataTable.display tbody th,.yasr table.dataTable.row-border tbody td,.yasr table.dataTable.row-border tbody th{border-top:1px solid #ddd}.yasr table.dataTable.display tbody tr:first-child td,.yasr table.dataTable.display tbody tr:first-child th,.yasr table.dataTable.row-border tbody tr:first-child td,.yasr table.dataTable.row-border tbody tr:first-child th{border-top:none}.yasr table.dataTable.cell-border tbody td,.yasr table.dataTable.cell-border tbody th{border-top:1px solid #ddd;border-right:1px solid #ddd}.yasr table.dataTable.cell-border tbody tr td:first-child,.yasr table.dataTable.cell-border tbody tr th:first-child{border-left:1px solid #ddd}.yasr table.dataTable.cell-border tbody tr:first-child td,.yasr table.dataTable.cell-border tbody tr:first-child th{border-top:none}.yasr table.dataTable.display tbody tr.odd,.yasr table.dataTable.stripe tbody tr.odd{background-color:#f9f9f9}.yasr table.dataTable.display tbody tr.odd.selected,.yasr table.dataTable.stripe tbody tr.odd.selected{background-color:#abb9d3}.yasr table.dataTable.display tbody tr.even:hover,.yasr table.dataTable.display tbody tr.odd:hover,.yasr table.dataTable.display tbody tr:hover,.yasr table.dataTable.hover tbody tr.even:hover,.yasr table.dataTable.hover tbody tr.odd:hover,.yasr table.dataTable.hover tbody tr:hover{background-color:#f5f5f5}.yasr table.dataTable.display tbody tr.even:hover.selected,.yasr table.dataTable.display tbody tr.odd:hover.selected,.yasr table.dataTable.display tbody tr:hover.selected,.yasr table.dataTable.hover tbody tr.even:hover.selected,.yasr table.dataTable.hover tbody tr.odd:hover.selected,.yasr table.dataTable.hover tbody tr:hover.selected{background-color:#a9b7d1}.yasr table.dataTable.display tbody tr>.sorting_1,.yasr table.dataTable.display tbody tr>.sorting_2,.yasr table.dataTable.display tbody tr>.sorting_3,.yasr table.dataTable.order-column tbody tr>.sorting_1,.yasr table.dataTable.order-column tbody tr>.sorting_2,.yasr table.dataTable.order-column tbody tr>.sorting_3{background-color:#f9f9f9}.yasr table.dataTable.display tbody tr.selected>.sorting_1,.yasr table.dataTable.display tbody tr.selected>.sorting_2,.yasr table.dataTable.display tbody tr.selected>.sorting_3,.yasr table.dataTable.order-column tbody tr.selected>.sorting_1,.yasr table.dataTable.order-column tbody tr.selected>.sorting_2,.yasr table.dataTable.order-column tbody tr.selected>.sorting_3{background-color:#acbad4}.yasr table.dataTable.display tbody tr.odd>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.odd>.sorting_1{background-color:#f1f1f1}.yasr table.dataTable.display tbody tr.odd>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.odd>.sorting_2{background-color:#f3f3f3}.yasr table.dataTable.display tbody tr.odd>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.odd>.sorting_3{background-color:#f5f5f5}.yasr table.dataTable.display tbody tr.odd.selected>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_1{background-color:#a6b3cd}.yasr table.dataTable.display tbody tr.odd.selected>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_2{background-color:#a7b5ce}.yasr table.dataTable.display tbody tr.odd.selected>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_3{background-color:#a9b6d0}.yasr table.dataTable.display tbody tr.even>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.even>.sorting_1{background-color:#f9f9f9}.yasr table.dataTable.display tbody tr.even>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.even>.sorting_2{background-color:#fbfbfb}.yasr table.dataTable.display tbody tr.even>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.even>.sorting_3{background-color:#fdfdfd}.yasr table.dataTable.display tbody tr.even.selected>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_1{background-color:#acbad4}.yasr table.dataTable.display tbody tr.even.selected>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_2{background-color:#adbbd6}.yasr table.dataTable.display tbody tr.even.selected>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_3{background-color:#afbdd8}.yasr table.dataTable.display tbody tr.even:hover>.sorting_1,.yasr table.dataTable.display tbody tr.odd:hover>.sorting_1,.yasr table.dataTable.display tbody tr:hover>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.even:hover>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.odd:hover>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr:hover>.sorting_1{background-color:#eaeaea}.yasr table.dataTable.display tbody tr.even:hover>.sorting_2,.yasr table.dataTable.display tbody tr.odd:hover>.sorting_2,.yasr table.dataTable.display tbody tr:hover>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.even:hover>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.odd:hover>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr:hover>.sorting_2{background-color:#ebebeb}.yasr table.dataTable.display tbody tr.even:hover>.sorting_3,.yasr table.dataTable.display tbody tr.odd:hover>.sorting_3,.yasr table.dataTable.display tbody tr:hover>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.even:hover>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.odd:hover>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr:hover>.sorting_3{background-color:#eee}.yasr table.dataTable.display tbody tr.even:hover.selected>.sorting_1,.yasr table.dataTable.display tbody tr.odd:hover.selected>.sorting_1,.yasr table.dataTable.display tbody tr:hover.selected>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.even:hover.selected>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.odd:hover.selected>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_1{background-color:#a1aec7}.yasr table.dataTable.display tbody tr.even:hover.selected>.sorting_2,.yasr table.dataTable.display tbody tr.odd:hover.selected>.sorting_2,.yasr table.dataTable.display tbody tr:hover.selected>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.even:hover.selected>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.odd:hover.selected>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_2{background-color:#a2afc8}.yasr table.dataTable.display tbody tr.even:hover.selected>.sorting_3,.yasr table.dataTable.display tbody tr.odd:hover.selected>.sorting_3,.yasr table.dataTable.display tbody tr:hover.selected>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.even:hover.selected>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.odd:hover.selected>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_3{background-color:#a4b2cb}.yasr table.dataTable.no-footer{border-bottom:1px solid #111}.yasr table.dataTable.nowrap td,.yasr table.dataTable.nowrap th{white-space:nowrap}.yasr table.dataTable.compact thead td,.yasr table.dataTable.compact thead th{padding:5px 9px}.yasr table.dataTable.compact tfoot td,.yasr table.dataTable.compact tfoot th{padding:5px 9px 3px}.yasr table.dataTable.compact tbody td,.yasr table.dataTable.compact tbody th{padding:4px 5px}.yasr table.dataTable td.dt-left,.yasr table.dataTable th.dt-left{text-align:left}.yasr table.dataTable td.dataTables_empty,.yasr table.dataTable td.dt-center,.yasr table.dataTable th.dt-center{text-align:center}.yasr table.dataTable td.dt-right,.yasr table.dataTable th.dt-right{text-align:right}.yasr table.dataTable td.dt-justify,.yasr table.dataTable th.dt-justify{text-align:justify}.yasr table.dataTable td.dt-nowrap,.yasr table.dataTable th.dt-nowrap{white-space:nowrap}.yasr table.dataTable tfoot td.dt-head-left,.yasr table.dataTable tfoot th.dt-head-left,.yasr table.dataTable thead td.dt-head-left,.yasr table.dataTable thead th.dt-head-left{text-align:left}.yasr table.dataTable tfoot td.dt-head-center,.yasr table.dataTable tfoot th.dt-head-center,.yasr table.dataTable thead td.dt-head-center,.yasr table.dataTable thead th.dt-head-center{text-align:center}.yasr table.dataTable tfoot td.dt-head-right,.yasr table.dataTable tfoot th.dt-head-right,.yasr table.dataTable thead td.dt-head-right,.yasr table.dataTable thead th.dt-head-right{text-align:right}.yasr table.dataTable tfoot td.dt-head-justify,.yasr table.dataTable tfoot th.dt-head-justify,.yasr table.dataTable thead td.dt-head-justify,.yasr table.dataTable thead th.dt-head-justify{text-align:justify}.yasr table.dataTable tfoot td.dt-head-nowrap,.yasr table.dataTable tfoot th.dt-head-nowrap,.yasr table.dataTable thead td.dt-head-nowrap,.yasr table.dataTable thead th.dt-head-nowrap{white-space:nowrap}.yasr table.dataTable tbody td.dt-body-left,.yasr table.dataTable tbody th.dt-body-left{text-align:left}.yasr table.dataTable tbody td.dt-body-center,.yasr table.dataTable tbody th.dt-body-center{text-align:center}.yasr table.dataTable tbody td.dt-body-right,.yasr table.dataTable tbody th.dt-body-right{text-align:right}.yasr table.dataTable tbody td.dt-body-justify,.yasr table.dataTable tbody th.dt-body-justify{text-align:justify}.yasr table.dataTable tbody td.dt-body-nowrap,.yasr table.dataTable tbody th.dt-body-nowrap{white-space:nowrap}.yasr table.dataTable,.yasr table.dataTable td,.yasr table.dataTable th{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .dataTables_wrapper{position:relative;clear:both;zoom:1}.yasr .dataTables_wrapper .dataTables_filter{float:right;text-align:right}.yasr .dataTables_wrapper .dataTables_filter input{margin-left:.5em}.yasr .dataTables_wrapper .dataTables_info{clear:both;float:left;padding-top:.755em}.yasr .dataTables_wrapper .dataTables_paginate{float:right;text-align:right;padding-top:.25em}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:.5em 1em;margin-left:2px;text-align:center;text-decoration:none!important;cursor:pointer;color:#333!important;border:1px solid transparent}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.current,.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover{color:#333!important;border:1px solid #cacaca;background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#fff),color-stop(100%,#dcdcdc));background:-webkit-linear-gradient(top,#fff 0,#dcdcdc 100%);background:-moz-linear-gradient(top,#fff 0,#dcdcdc 100%);background:-ms-linear-gradient(top,#fff 0,#dcdcdc 100%);background:-o-linear-gradient(top,#fff 0,#dcdcdc 100%);background:linear-gradient(to bottom,#fff 0,#dcdcdc 100%)}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.disabled,.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active,.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover{cursor:default;color:#666!important;border:1px solid transparent;background:0 0;box-shadow:none}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button:hover{color:#fff!important;border:1px solid #111;background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#585858),color-stop(100%,#111));background:-webkit-linear-gradient(top,#585858 0,#111 100%);background:-moz-linear-gradient(top,#585858 0,#111 100%);background:-ms-linear-gradient(top,#585858 0,#111 100%);background:-o-linear-gradient(top,#585858 0,#111 100%);background:linear-gradient(to bottom,#585858 0,#111 100%)}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button:active{outline:0;background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#2b2b2b),color-stop(100%,#0c0c0c));background:-webkit-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:-moz-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:-ms-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:-o-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:linear-gradient(to bottom,#2b2b2b 0,#0c0c0c 100%);box-shadow:inset 0 0 3px #111}.yasr .dataTables_wrapper .dataTables_processing{position:absolute;top:50%;left:50%;width:100%;height:40px;margin-left:-50%;margin-top:-25px;padding-top:20px;text-align:center;font-size:1.2em;background:-webkit-gradient(linear,left top,right top,color-stop(0,rgba(255,255,255,0)),color-stop(25%,rgba(255,255,255,.9)),color-stop(75%,rgba(255,255,255,.9)),color-stop(100%,rgba(255,255,255,0)));background:-webkit-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:-moz-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:-ms-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:-o-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:linear-gradient(to right,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%)}.yasr .dataTables_wrapper .dataTables_filter,.yasr .dataTables_wrapper .dataTables_info,.yasr .dataTables_wrapper .dataTables_length,.yasr .dataTables_wrapper .dataTables_paginate,.yasr .dataTables_wrapper .dataTables_processing{color:#333}.yasr .dataTables_wrapper .dataTables_scroll{clear:both}.yasr .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody{-webkit-overflow-scrolling:touch}.yasr .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td>div.dataTables_sizing,.yasr .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th>div.dataTables_sizing{height:0;overflow:hidden;margin:0!important;padding:0!important}.yasr .dataTables_wrapper.no-footer .dataTables_scrollBody{border-bottom:1px solid #111}.yasr .dataTables_wrapper.no-footer div.dataTables_scrollBody table,.yasr .dataTables_wrapper.no-footer div.dataTables_scrollHead table{border-bottom:none}.yasr .dataTables_wrapper:after{visibility:hidden;display:block;content:"";clear:both;height:0}@media screen and (max-width:767px){.yasr .dataTables_wrapper .dataTables_info,.yasr .dataTables_wrapper .dataTables_paginate{float:none;text-align:center}.yasr .dataTables_wrapper .dataTables_paginate{margin-top:.5em}}@media screen and (max-width:640px){.yasr .dataTables_wrapper .dataTables_filter,.yasr .dataTables_wrapper .dataTables_length{float:none;text-align:center}.yasr .dataTables_wrapper .dataTables_filter{margin-top:.5em}}.yasr table.pvtTable{font-family:arial;font-size:8pt;text-align:left;border-collapse:collapse}.yasr table.pvtTable tr th{background-color:#e6EEEE;border:1px solid #CDCDCD;font-size:8pt;padding:5px}.yasr table.pvtTable .pvtColLabel{text-align:center}.yasr table.pvtTable .pvtTotalLabel{text-align:right}.yasr table.pvtTable tr td{color:#3D3D3D;padding:5px;background-color:#FFF;border:1px solid #CDCDCD;vertical-align:top;text-align:right}.yasr .pvtGrandTotal,.yasr .pvtTotal{font-weight:700}.yasr .pvtVals{text-align:center}.yasr .pvtAggregator{margin-bottom:5px}.yasr .pvtAxisContainer,.yasr .pvtVals{border:1px solid gray;background:#EEE;padding:5px;min-width:20px;min-height:20px}.yasr .pvtAxisContainer li{padding:8px 6px;list-style-type:none;cursor:move}.yasr .pvtAxisContainer li.pvtPlaceholder{-webkit-border-radius:5px;padding:3px 15px;-moz-border-radius:5px;border-radius:5px;border:1px dashed #aaa}.yasr .pvtAxisContainer li span.pvtAttr{background:#F3F3F3;border:1px solid #DEDEDE;padding:2px 5px;white-space:nowrap;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.yasr .pvtTriangle{cursor:pointer;color:grey}.yasr .pvtHorizList li{display:inline}.yasr .pvtVertList{vertical-align:top}.yasr .pvtFilteredAttribute{font-style:italic}.yasr .pvtFilterBox{z-index:100;width:280px;border:1px solid gray;background-color:#fff;position:absolute;padding:20px;text-align:center}.yasr .pvtFilterBox h4{margin:0}.yasr .pvtCheckContainer{text-align:left;overflow:scroll;width:100%;max-height:200px}.yasr .pvtCheckContainer p{margin:5px}.yasr .CodeMirror{font-family:monospace;height:300px}.yasr .CodeMirror-lines{padding:4px 0}.yasr .CodeMirror pre{padding:0 4px}.yasr .CodeMirror-gutter-filler,.yasr .CodeMirror-scrollbar-filler{background-color:#fff}.yasr .CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.yasr .CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .CodeMirror-guttermarker{color:#000}.yasr .CodeMirror-guttermarker-subtle{color:#999}.yasr .CodeMirror div.CodeMirror-cursor{border-left:1px solid #000}.yasr .CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.yasr .CodeMirror.cm-fat-cursor div.CodeMirror-cursor{width:auto;border:0;background:#7e7}.yasr .CodeMirror.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.yasr .cm-animate-fat-cursor{width:auto;border:0;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.yasr .cm-tab{display:inline-block;text-decoration:inherit}.yasr .CodeMirror-ruler{border-left:1px solid #ccc;position:absolute}.yasr .cm-s-default .cm-keyword{color:#708}.yasr .cm-s-default .cm-atom{color:#219}.yasr .cm-s-default .cm-number{color:#164}.yasr .cm-s-default .cm-def{color:#00f}.yasr .cm-s-default .cm-variable-2{color:#05a}.yasr .cm-s-default .cm-variable-3{color:#085}.yasr .cm-s-default .cm-comment{color:#a50}.yasr .cm-s-default .cm-string{color:#a11}.yasr .cm-s-default .cm-string-2{color:#f50}.yasr .cm-s-default .cm-meta,.yasr .cm-s-default .cm-qualifier{color:#555}.yasr .cm-s-default .cm-builtin{color:#30a}.yasr .cm-s-default .cm-bracket{color:#997}.yasr .cm-s-default .cm-tag{color:#170}.yasr .cm-s-default .cm-attribute{color:#00c}.yasr .cm-s-default .cm-header{color:#00f}.yasr .cm-s-default .cm-quote{color:#090}.yasr .cm-s-default .cm-hr{color:#999}.yasr .cm-s-default .cm-link{color:#00c}.yasr .cm-negative{color:#d44}.yasr .cm-positive{color:#292}.yasr .cm-header,.yasr .cm-strong{font-weight:700}.yasr .cm-em{font-style:italic}.yasr .cm-link{text-decoration:underline}.yasr .cm-strikethrough{text-decoration:line-through}.yasr .cm-invalidchar,.yasr .cm-s-default .cm-error{color:red}.yasr div.CodeMirror span.CodeMirror-matchingbracket{color:#0f0}.yasr div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#f22}.yasr .CodeMirror-matchingtag{background:rgba(255,150,0,.3)}.yasr .CodeMirror-activeline-background{background:#e8f2ff}.yasr .CodeMirror{line-height:1;position:relative;overflow:hidden;background:#fff;color:#000}.yasr .CodeMirror-scroll{overflow:scroll!important;margin-bottom:-30px;margin-right:-30px;padding-bottom:30px;height:100%;outline:0;position:relative;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .CodeMirror-sizer{position:relative;border-right:30px solid transparent;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .CodeMirror-gutter-filler,.yasr .CodeMirror-hscrollbar,.yasr .CodeMirror-scrollbar-filler,.yasr .CodeMirror-vscrollbar{position:absolute;z-index:6;display:none}.yasr .CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.yasr .CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.yasr .CodeMirror-scrollbar-filler{right:0;bottom:0}.yasr .CodeMirror-gutter-filler{left:0;bottom:0}.yasr .CodeMirror-gutters{position:absolute;left:0;top:0;z-index:3}.yasr .CodeMirror-gutter{white-space:normal;height:100%;-moz-box-sizing:content-box;box-sizing:content-box;display:inline-block;margin-bottom:-30px}.yasr .CodeMirror-gutter-wrapper{position:absolute;z-index:4;height:100%}.yasr .CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.yasr .CodeMirror-lines{cursor:text;min-height:1px}.yasr .CodeMirror pre{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:0 0;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible}.yasr .CodeMirror-wrap pre{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.yasr .CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.yasr .CodeMirror-linewidget{position:relative;z-index:2;overflow:auto}.yasr .CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.yasr .CodeMirror-measure pre{position:static}.yasr .CodeMirror div.CodeMirror-cursor{position:absolute;border-right:none;width:0}.yasr div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}.yasr .CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.yasr .CodeMirror-selected{background:#d9d9d9}.yasr .CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.yasr .CodeMirror-crosshair{cursor:crosshair}.yasr .cm-searching{background:#ffa;background:rgba(255,255,0,.4)}.yasr .cm-force-border{padding-right:.1px}@media print{.yasr .CodeMirror div.CodeMirror-cursors{visibility:hidden}}.yasr .cm-tab-wrap-hack:after{content:''}.yasr span.CodeMirror-selectedtext{background:0 0}.yasr .CodeMirror-foldmarker{color:#00f;text-shadow:#b9f 1px 1px 2px,#b9f -1px -1px 2px,#b9f 1px -1px 2px,#b9f -1px 1px 2px;font-family:arial;line-height:.3;cursor:pointer}.yasr .CodeMirror-foldgutter{width:.7em}.yasr .CodeMirror-foldgutter-folded,.yasr .CodeMirror-foldgutter-open{cursor:pointer}.yasr .CodeMirror-foldgutter-open:after{content:"\25BE"}.yasr .CodeMirror-foldgutter-folded:after{content:"\25B8"}.yasr a{color:#428bca;text-decoration:none}.yasr a:active,.yasr a:hover{outline:0;color:#2a6496;text-decoration:underline}.yasr th{text-align:left}.yasr .yasr_header *{z-index:5;position:relative}.yasr .yasr_header>*{margin-left:6px}.yasr .yasr_btn{color:#333;border:1px solid transparent;background-color:#fff;border-color:#ccc;border-width:1px;display:inline-block;text-align:center;vertical-align:middle;cursor:pointer;white-space:nowrap;padding:6px 12px;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-appearance:button;overflow:visible;box-sizing:border-box}.yasr .yasr_btn.btn_icon{padding:4px 8px}.yasr .yasr_btn.disabled,.yasr .yasr_btn[disabled]{cursor:default;opacity:.5;filter:alpha(opacity=50);-webkit-box-shadow:none;box-shadow:none}.yasr .yasr_btn:hover{outline:0;background-color:#ebebeb;border-color:#adadad}.yasr .yasr_btn.selected,.yasr .yasr_btn:focus{color:#fff;outline:0;background-color:#337ab7;border-color:#337ab7}.yasr .yasr_btn.btn_icon:focus{color:#333;border:1px solid transparent;background-color:#fff;border-color:#ccc}.yasr .yasr_downloadIcon div{height:15px;width:15px}.yasr .yasr_btnGroup{display:inline-block;vertical-align:middle}.yasr .yasr_btnGroup>button:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0}.yasr .yasr_btnGroup>button:last-child:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.yasr .yasr_btnGroup>button:not(:first-child):not(:last-child){border-radius:0}.yasr .yasr_btnGroup button+button{margin-left:-1px}.yasr .booleanResult{width:70px;margin:0 auto;vertical-align:middle}.yasr .booleanResult svg{margin-bottom:-10px;margin-right:7px}.yasr .errorResult{padding:10px}.yasr .errorResult span.exception{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em;background-color:#d9534f}.yasr .errorResult pre{display:block;padding:10px;margin:10px 0;font-size:13px;line-height:1.42857;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}.yasr .yasr_results .CodeMirror{border:1px solid #d1d1d1;margin-top:5px;height:100%}.yasr .dataTables_wrapper .dataTables_length{float:right;margin-left:10px}.yasr .dataTables_wrapper .dataTables_length label,.yasr .dataTables_wrapper .dataTables_length select{vertical-align:middle}.yasr table.dataTable thead th{background:0 0!important;border-right:1px dotted gray;padding:7px 0}.yasr table.dataTable thead th:first-child,.yasr table.dataTable thead th:last-child{border-right:0}.yasr table.dataTable thead th span{margin-left:5px}.yasr table.dataTable td div{-ms-word-break:break-all;word-break:break-all;word-break:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;-ms-hyphens:auto;hyphens:auto;padding:0 5px}.yasr .sortIcons{float:right;width:8px;height:13px;margin-right:10px}.yasr .pivotTable{margin-top:5px}.yasr .pivotTable>table{background-color:#fff}.yasr .pivotTable td.pvtAxisContainer,.yasr .pivotTable td.pvtVals{border:1px solid #ddd;background-color:transparent}.yasr .pivotTable li span.pvtAttr{background-color:#337ab7;color:#fff;padding:4px 7px}.yasr .pivotTable li span.pvtAttr svg{fill:#fff}.yasr .pivotTable li span.pvtAttr div{margin-left:6px;vertical-align:middle}.yasr .pivotTable .pvtCols{vertical-align:top}.yasr .pivotTable table.pvtTable tr th{background-color:#f2f2f2}.yasr .pivotTable table.pvtTable tr th.pvtAxisLabel{background-color:#337ab7;color:#fff}.yasr .pivotTable .containerHeader{margin-left:8px;margin-bottom:8px;font-style:italic;font-size:110%;color:#999;text-align:left}.yasr .pivotTable .pvtAttr .svgImg{width:14px;height:14px}.yasr .pivotTable .node{border:1px solid #fff;font:10px sans-serif;line-height:12px;overflow:hidden;position:absolute;text-indent:2px}.yasr .openPivotGchart{float:right;position:relative;display:none;top:-38px;margin-bottom:-38px}.yasr .openGchartBtn{float:right;position:relative;top:-35px;margin-bottom:-35px}.yasr .gchartWrapper{width:100%;height:600px;margin-top:2px}.modal-dialog.google-visualization-charteditor-dialog{z-index:11;width:auto;margin:inherit}div.modal-dialog.google-visualization-charteditor-dialog{z-index:100} | rigdern/cdnjs | ajax/libs/yasgui/0.0.8/yasgui.min.css | CSS | mit | 181,242 |
.yasgui{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857;color:#333;background-color:#fff;/*! normalize.css v3.0.2 | MIT License | git.io/normalize *//*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@font-face { font-family:'Glyphicons Halflings';src:url(../fonts/bootstrap/glyphicons-halflings-regular.eot);src:url(../fonts/bootstrap/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/bootstrap/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/bootstrap/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/bootstrap/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-viewport{width:device-width}.yasgui html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}.yasgui body{margin:0}.yasgui article,.yasgui aside,.yasgui details,.yasgui figcaption,.yasgui figure,.yasgui footer,.yasgui header,.yasgui hgroup,.yasgui main,.yasgui menu,.yasgui nav,.yasgui section,.yasgui summary{display:block}.yasgui audio,.yasgui canvas,.yasgui progress,.yasgui video{display:inline-block;vertical-align:baseline}.yasgui audio:not([controls]){display:none;height:0}.yasgui [hidden],.yasgui template{display:none}.yasgui a{background-color:transparent}.yasgui a:active,.yasgui a:hover{outline:0}.yasgui b,.yasgui strong{font-weight:700}.yasgui dfn{font-style:italic}.yasgui h1{margin:.67em 0}.yasgui mark{background:#ff0;color:#000}.yasgui sub,.yasgui sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}.yasgui sup{top:-.5em}.yasgui sub{bottom:-.25em}.yasgui img{border:0}.yasgui svg:not(:root){overflow:hidden}.yasgui hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}.yasgui pre{overflow:auto}.yasgui code,.yasgui kbd,.yasgui pre,.yasgui samp{font-size:1em}.yasgui button,.yasgui input,.yasgui optgroup,.yasgui select,.yasgui textarea{color:inherit;font:inherit;margin:0}.yasgui button{overflow:visible}.yasgui button,.yasgui select{text-transform:none}.yasgui button,.yasgui html input[type=button],.yasgui input[type=reset],.yasgui input[type=submit]{-webkit-appearance:button;cursor:pointer}.yasgui button[disabled],.yasgui html input[disabled]{cursor:default}.yasgui button::-moz-focus-inner,.yasgui input::-moz-focus-inner{border:0;padding:0}.yasgui input[type=radio],.yasgui input[type=checkbox]{box-sizing:border-box;padding:0}.yasgui input[type=number]::-webkit-inner-spin-button,.yasgui input[type=number]::-webkit-outer-spin-button{height:auto}.yasgui input[type=search]::-webkit-search-cancel-button,.yasgui input[type=search]::-webkit-search-decoration{-webkit-appearance:none}.yasgui textarea{overflow:auto}.yasgui optgroup{font-weight:700}.yasgui table{border-collapse:collapse;border-spacing:0}.yasgui td,.yasgui th{padding:0}@media print{.yasgui *,.yasgui :after,.yasgui :before{background:0 0!important;color:#000!important;box-shadow:none!important;text-shadow:none!important}.yasgui a,.yasgui a:visited{text-decoration:underline}.yasgui a[href]:after{content:" (" attr(href) ")"}.yasgui abbr[title]:after{content:" (" attr(title) ")"}.yasgui a[href^="#"]:after,.yasgui a[href^="javascript:"]:after{content:""}.yasgui blockquote,.yasgui pre{border:1px solid #999;page-break-inside:avoid}.yasgui thead{display:table-header-group}.yasgui img,.yasgui tr{page-break-inside:avoid}.yasgui img{max-width:100%!important}.yasgui h2,.yasgui h3,.yasgui p{orphans:3;widows:3}.yasgui h2,.yasgui h3{page-break-after:avoid}.yasgui select{background:#fff!important}.yasgui .navbar{display:none}.yasgui .btn>.caret,.yasgui .dropup>.btn>.caret{border-top-color:#000!important}.yasgui .label{border:1px solid #000}.yasgui .table{border-collapse:collapse!important}.yasgui .table td,.yasgui .table th{background-color:#fff!important}.yasgui .table-bordered td,.yasgui .table-bordered th{border:1px solid #ddd!important}}.yasgui .glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.yasgui .glyphicon-asterisk:before{content:"\2a"}.yasgui .glyphicon-plus:before{content:"\2b"}.yasgui .glyphicon-eur:before,.yasgui .glyphicon-euro:before{content:"\20ac"}.yasgui .glyphicon-minus:before{content:"\2212"}.yasgui .glyphicon-cloud:before{content:"\2601"}.yasgui .glyphicon-envelope:before{content:"\2709"}.yasgui .glyphicon-pencil:before{content:"\270f"}.yasgui .glyphicon-glass:before{content:"\e001"}.yasgui .glyphicon-music:before{content:"\e002"}.yasgui .glyphicon-search:before{content:"\e003"}.yasgui .glyphicon-heart:before{content:"\e005"}.yasgui .glyphicon-star:before{content:"\e006"}.yasgui .glyphicon-star-empty:before{content:"\e007"}.yasgui .glyphicon-user:before{content:"\e008"}.yasgui .glyphicon-film:before{content:"\e009"}.yasgui .glyphicon-th-large:before{content:"\e010"}.yasgui .glyphicon-th:before{content:"\e011"}.yasgui .glyphicon-th-list:before{content:"\e012"}.yasgui .glyphicon-ok:before{content:"\e013"}.yasgui .glyphicon-remove:before{content:"\e014"}.yasgui .glyphicon-zoom-in:before{content:"\e015"}.yasgui .glyphicon-zoom-out:before{content:"\e016"}.yasgui .glyphicon-off:before{content:"\e017"}.yasgui .glyphicon-signal:before{content:"\e018"}.yasgui .glyphicon-cog:before{content:"\e019"}.yasgui .glyphicon-trash:before{content:"\e020"}.yasgui .glyphicon-home:before{content:"\e021"}.yasgui .glyphicon-file:before{content:"\e022"}.yasgui .glyphicon-time:before{content:"\e023"}.yasgui .glyphicon-road:before{content:"\e024"}.yasgui .glyphicon-download-alt:before{content:"\e025"}.yasgui .glyphicon-download:before{content:"\e026"}.yasgui .glyphicon-upload:before{content:"\e027"}.yasgui .glyphicon-inbox:before{content:"\e028"}.yasgui .glyphicon-play-circle:before{content:"\e029"}.yasgui .glyphicon-repeat:before{content:"\e030"}.yasgui .glyphicon-refresh:before{content:"\e031"}.yasgui .glyphicon-list-alt:before{content:"\e032"}.yasgui .glyphicon-lock:before{content:"\e033"}.yasgui .glyphicon-flag:before{content:"\e034"}.yasgui .glyphicon-headphones:before{content:"\e035"}.yasgui .glyphicon-volume-off:before{content:"\e036"}.yasgui .glyphicon-volume-down:before{content:"\e037"}.yasgui .glyphicon-volume-up:before{content:"\e038"}.yasgui .glyphicon-qrcode:before{content:"\e039"}.yasgui .glyphicon-barcode:before{content:"\e040"}.yasgui .glyphicon-tag:before{content:"\e041"}.yasgui .glyphicon-tags:before{content:"\e042"}.yasgui .glyphicon-book:before{content:"\e043"}.yasgui .glyphicon-bookmark:before{content:"\e044"}.yasgui .glyphicon-print:before{content:"\e045"}.yasgui .glyphicon-camera:before{content:"\e046"}.yasgui .glyphicon-font:before{content:"\e047"}.yasgui .glyphicon-bold:before{content:"\e048"}.yasgui .glyphicon-italic:before{content:"\e049"}.yasgui .glyphicon-text-height:before{content:"\e050"}.yasgui .glyphicon-text-width:before{content:"\e051"}.yasgui .glyphicon-align-left:before{content:"\e052"}.yasgui .glyphicon-align-center:before{content:"\e053"}.yasgui .glyphicon-align-right:before{content:"\e054"}.yasgui .glyphicon-align-justify:before{content:"\e055"}.yasgui .glyphicon-list:before{content:"\e056"}.yasgui .glyphicon-indent-left:before{content:"\e057"}.yasgui .glyphicon-indent-right:before{content:"\e058"}.yasgui .glyphicon-facetime-video:before{content:"\e059"}.yasgui .glyphicon-picture:before{content:"\e060"}.yasgui .glyphicon-map-marker:before{content:"\e062"}.yasgui .glyphicon-adjust:before{content:"\e063"}.yasgui .glyphicon-tint:before{content:"\e064"}.yasgui .glyphicon-edit:before{content:"\e065"}.yasgui .glyphicon-share:before{content:"\e066"}.yasgui .glyphicon-check:before{content:"\e067"}.yasgui .glyphicon-move:before{content:"\e068"}.yasgui .glyphicon-step-backward:before{content:"\e069"}.yasgui .glyphicon-fast-backward:before{content:"\e070"}.yasgui .glyphicon-backward:before{content:"\e071"}.yasgui .glyphicon-play:before{content:"\e072"}.yasgui .glyphicon-pause:before{content:"\e073"}.yasgui .glyphicon-stop:before{content:"\e074"}.yasgui .glyphicon-forward:before{content:"\e075"}.yasgui .glyphicon-fast-forward:before{content:"\e076"}.yasgui .glyphicon-step-forward:before{content:"\e077"}.yasgui .glyphicon-eject:before{content:"\e078"}.yasgui .glyphicon-chevron-left:before{content:"\e079"}.yasgui .glyphicon-chevron-right:before{content:"\e080"}.yasgui .glyphicon-plus-sign:before{content:"\e081"}.yasgui .glyphicon-minus-sign:before{content:"\e082"}.yasgui .glyphicon-remove-sign:before{content:"\e083"}.yasgui .glyphicon-ok-sign:before{content:"\e084"}.yasgui .glyphicon-question-sign:before{content:"\e085"}.yasgui .glyphicon-info-sign:before{content:"\e086"}.yasgui .glyphicon-screenshot:before{content:"\e087"}.yasgui .glyphicon-remove-circle:before{content:"\e088"}.yasgui .glyphicon-ok-circle:before{content:"\e089"}.yasgui .glyphicon-ban-circle:before{content:"\e090"}.yasgui .glyphicon-arrow-left:before{content:"\e091"}.yasgui .glyphicon-arrow-right:before{content:"\e092"}.yasgui .glyphicon-arrow-up:before{content:"\e093"}.yasgui .glyphicon-arrow-down:before{content:"\e094"}.yasgui .glyphicon-share-alt:before{content:"\e095"}.yasgui .glyphicon-resize-full:before{content:"\e096"}.yasgui .glyphicon-resize-small:before{content:"\e097"}.yasgui .glyphicon-exclamation-sign:before{content:"\e101"}.yasgui .glyphicon-gift:before{content:"\e102"}.yasgui .glyphicon-leaf:before{content:"\e103"}.yasgui .glyphicon-fire:before{content:"\e104"}.yasgui .glyphicon-eye-open:before{content:"\e105"}.yasgui .glyphicon-eye-close:before{content:"\e106"}.yasgui .glyphicon-warning-sign:before{content:"\e107"}.yasgui .glyphicon-plane:before{content:"\e108"}.yasgui .glyphicon-calendar:before{content:"\e109"}.yasgui .glyphicon-random:before{content:"\e110"}.yasgui .glyphicon-comment:before{content:"\e111"}.yasgui .glyphicon-magnet:before{content:"\e112"}.yasgui .glyphicon-chevron-up:before{content:"\e113"}.yasgui .glyphicon-chevron-down:before{content:"\e114"}.yasgui .glyphicon-retweet:before{content:"\e115"}.yasgui .glyphicon-shopping-cart:before{content:"\e116"}.yasgui .glyphicon-folder-close:before{content:"\e117"}.yasgui .glyphicon-folder-open:before{content:"\e118"}.yasgui .glyphicon-resize-vertical:before{content:"\e119"}.yasgui .glyphicon-resize-horizontal:before{content:"\e120"}.yasgui .glyphicon-hdd:before{content:"\e121"}.yasgui .glyphicon-bullhorn:before{content:"\e122"}.yasgui .glyphicon-bell:before{content:"\e123"}.yasgui .glyphicon-certificate:before{content:"\e124"}.yasgui .glyphicon-thumbs-up:before{content:"\e125"}.yasgui .glyphicon-thumbs-down:before{content:"\e126"}.yasgui .glyphicon-hand-right:before{content:"\e127"}.yasgui .glyphicon-hand-left:before{content:"\e128"}.yasgui .glyphicon-hand-up:before{content:"\e129"}.yasgui .glyphicon-hand-down:before{content:"\e130"}.yasgui .glyphicon-circle-arrow-right:before{content:"\e131"}.yasgui .glyphicon-circle-arrow-left:before{content:"\e132"}.yasgui .glyphicon-circle-arrow-up:before{content:"\e133"}.yasgui .glyphicon-circle-arrow-down:before{content:"\e134"}.yasgui .glyphicon-globe:before{content:"\e135"}.yasgui .glyphicon-wrench:before{content:"\e136"}.yasgui .glyphicon-tasks:before{content:"\e137"}.yasgui .glyphicon-filter:before{content:"\e138"}.yasgui .glyphicon-briefcase:before{content:"\e139"}.yasgui .glyphicon-fullscreen:before{content:"\e140"}.yasgui .glyphicon-dashboard:before{content:"\e141"}.yasgui .glyphicon-paperclip:before{content:"\e142"}.yasgui .glyphicon-heart-empty:before{content:"\e143"}.yasgui .glyphicon-link:before{content:"\e144"}.yasgui .glyphicon-phone:before{content:"\e145"}.yasgui .glyphicon-pushpin:before{content:"\e146"}.yasgui .glyphicon-usd:before{content:"\e148"}.yasgui .glyphicon-gbp:before{content:"\e149"}.yasgui .glyphicon-sort:before{content:"\e150"}.yasgui .glyphicon-sort-by-alphabet:before{content:"\e151"}.yasgui .glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.yasgui .glyphicon-sort-by-order:before{content:"\e153"}.yasgui .glyphicon-sort-by-order-alt:before{content:"\e154"}.yasgui .glyphicon-sort-by-attributes:before{content:"\e155"}.yasgui .glyphicon-sort-by-attributes-alt:before{content:"\e156"}.yasgui .glyphicon-unchecked:before{content:"\e157"}.yasgui .glyphicon-expand:before{content:"\e158"}.yasgui .glyphicon-collapse-down:before{content:"\e159"}.yasgui .glyphicon-collapse-up:before{content:"\e160"}.yasgui .glyphicon-log-in:before{content:"\e161"}.yasgui .glyphicon-flash:before{content:"\e162"}.yasgui .glyphicon-log-out:before{content:"\e163"}.yasgui .glyphicon-new-window:before{content:"\e164"}.yasgui .glyphicon-record:before{content:"\e165"}.yasgui .glyphicon-save:before{content:"\e166"}.yasgui .glyphicon-open:before{content:"\e167"}.yasgui .glyphicon-saved:before{content:"\e168"}.yasgui .glyphicon-import:before{content:"\e169"}.yasgui .glyphicon-export:before{content:"\e170"}.yasgui .glyphicon-send:before{content:"\e171"}.yasgui .glyphicon-floppy-disk:before{content:"\e172"}.yasgui .glyphicon-floppy-saved:before{content:"\e173"}.yasgui .glyphicon-floppy-remove:before{content:"\e174"}.yasgui .glyphicon-floppy-save:before{content:"\e175"}.yasgui .glyphicon-floppy-open:before{content:"\e176"}.yasgui .glyphicon-credit-card:before{content:"\e177"}.yasgui .glyphicon-transfer:before{content:"\e178"}.yasgui .glyphicon-cutlery:before{content:"\e179"}.yasgui .glyphicon-header:before{content:"\e180"}.yasgui .glyphicon-compressed:before{content:"\e181"}.yasgui .glyphicon-earphone:before{content:"\e182"}.yasgui .glyphicon-phone-alt:before{content:"\e183"}.yasgui .glyphicon-tower:before{content:"\e184"}.yasgui .glyphicon-stats:before{content:"\e185"}.yasgui .glyphicon-sd-video:before{content:"\e186"}.yasgui .glyphicon-hd-video:before{content:"\e187"}.yasgui .glyphicon-subtitles:before{content:"\e188"}.yasgui .glyphicon-sound-stereo:before{content:"\e189"}.yasgui .glyphicon-sound-dolby:before{content:"\e190"}.yasgui .glyphicon-sound-5-1:before{content:"\e191"}.yasgui .glyphicon-sound-6-1:before{content:"\e192"}.yasgui .glyphicon-sound-7-1:before{content:"\e193"}.yasgui .glyphicon-copyright-mark:before{content:"\e194"}.yasgui .glyphicon-registration-mark:before{content:"\e195"}.yasgui .glyphicon-cloud-download:before{content:"\e197"}.yasgui .glyphicon-cloud-upload:before{content:"\e198"}.yasgui .glyphicon-tree-conifer:before{content:"\e199"}.yasgui .glyphicon-tree-deciduous:before{content:"\e200"}.yasgui *,.yasgui :after,.yasgui :before{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui html{font-size:10px;-webkit-tap-highlight-color:transparent}.yasgui body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857;color:#333;background-color:#fff}.yasgui button,.yasgui input,.yasgui select,.yasgui textarea{font-family:inherit;font-size:inherit;line-height:inherit}.yasgui a{color:#337ab7;text-decoration:none}.yasgui a:focus,.yasgui a:hover{color:#23527c;text-decoration:underline}.yasgui a:focus{outline:dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.yasgui figure{margin:0}.yasgui img{vertical-align:middle}.yasgui .img-responsive{display:block;max-width:100%;height:auto}.yasgui .img-rounded{border-radius:6px}.yasgui .img-thumbnail{padding:4px;line-height:1.42857;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out;display:inline-block;max-width:100%;height:auto}.yasgui .img-circle{border-radius:50%}.yasgui hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.yasgui .sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);border:0}.yasgui .sr-only-focusable:active,.yasgui .sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}.yasgui .h1,.yasgui .h2,.yasgui .h3,.yasgui .h4,.yasgui .h5,.yasgui .h6,.yasgui h1,.yasgui h2,.yasgui h3,.yasgui h4,.yasgui h5,.yasgui h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.yasgui .h1 .small,.yasgui .h1 small,.yasgui .h2 .small,.yasgui .h2 small,.yasgui .h3 .small,.yasgui .h3 small,.yasgui .h4 .small,.yasgui .h4 small,.yasgui .h5 .small,.yasgui .h5 small,.yasgui .h6 .small,.yasgui .h6 small,.yasgui h1 .small,.yasgui h1 small,.yasgui h2 .small,.yasgui h2 small,.yasgui h3 .small,.yasgui h3 small,.yasgui h4 .small,.yasgui h4 small,.yasgui h5 .small,.yasgui h5 small,.yasgui h6 .small,.yasgui h6 small{font-weight:400;line-height:1;color:#777}.yasgui .h1,.yasgui .h2,.yasgui .h3,.yasgui h1,.yasgui h2,.yasgui h3{margin-top:20px;margin-bottom:10px}.yasgui .h1 .small,.yasgui .h1 small,.yasgui .h2 .small,.yasgui .h2 small,.yasgui .h3 .small,.yasgui .h3 small,.yasgui h1 .small,.yasgui h1 small,.yasgui h2 .small,.yasgui h2 small,.yasgui h3 .small,.yasgui h3 small{font-size:65%}.yasgui .h4,.yasgui .h5,.yasgui .h6,.yasgui h4,.yasgui h5,.yasgui h6{margin-top:10px;margin-bottom:10px}.yasgui .h4 .small,.yasgui .h4 small,.yasgui .h5 .small,.yasgui .h5 small,.yasgui .h6 .small,.yasgui .h6 small,.yasgui h4 .small,.yasgui h4 small,.yasgui h5 .small,.yasgui h5 small,.yasgui h6 .small,.yasgui h6 small{font-size:75%}.yasgui .h1,.yasgui h1{font-size:36px}.yasgui .h2,.yasgui h2{font-size:30px}.yasgui .h3,.yasgui h3{font-size:24px}.yasgui .h4,.yasgui h4{font-size:18px}.yasgui .h5,.yasgui h5{font-size:14px}.yasgui .h6,.yasgui h6{font-size:12px}.yasgui p{margin:0 0 10px}.yasgui .lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.yasgui .lead{font-size:21px}}.yasgui .small,.yasgui small{font-size:85%}.yasgui .mark,.yasgui mark{background-color:#fcf8e3;padding:.2em}.yasgui .text-left{text-align:left}.yasgui .text-right{text-align:right}.yasgui .text-center{text-align:center}.yasgui .text-justify{text-align:justify}.yasgui .text-nowrap{white-space:nowrap}.yasgui .text-lowercase{text-transform:lowercase}.yasgui .text-uppercase{text-transform:uppercase}.yasgui .text-capitalize{text-transform:capitalize}.yasgui .text-muted{color:#777}.yasgui .text-primary{color:#337ab7}.yasgui a.text-primary:hover{color:#286090}.yasgui .text-success{color:#3c763d}.yasgui a.text-success:hover{color:#2b542c}.yasgui .text-info{color:#31708f}.yasgui a.text-info:hover{color:#245269}.yasgui .text-warning{color:#8a6d3b}.yasgui a.text-warning:hover{color:#66512c}.yasgui .text-danger{color:#a94442}.yasgui a.text-danger:hover{color:#843534}.yasgui .bg-primary{color:#fff;background-color:#337ab7}.yasgui a.bg-primary:hover{background-color:#286090}.yasgui .bg-success{background-color:#dff0d8}.yasgui a.bg-success:hover{background-color:#c1e2b3}.yasgui .bg-info{background-color:#d9edf7}.yasgui a.bg-info:hover{background-color:#afd9ee}.yasgui .bg-warning{background-color:#fcf8e3}.yasgui a.bg-warning:hover{background-color:#f7ecb5}.yasgui .bg-danger{background-color:#f2dede}.yasgui a.bg-danger:hover{background-color:#e4b9b9}.yasgui .page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}.yasgui ol,.yasgui ul{margin-top:0;margin-bottom:10px}.yasgui ol ol,.yasgui ol ul,.yasgui ul ol,.yasgui ul ul{margin-bottom:0}.yasgui .list-unstyled{padding-left:0;list-style:none}.yasgui .list-inline{padding-left:0;list-style:none;margin-left:-5px}.yasgui .list-inline>li{display:inline-block;padding-left:5px;padding-right:5px}.yasgui dl{margin-top:0;margin-bottom:20px}.yasgui dd,.yasgui dt{line-height:1.42857}.yasgui dt{font-weight:700}.yasgui dd{margin-left:0}.yasgui .dl-horizontal dd:after,.yasgui .dl-horizontal dd:before{content:" ";display:table}.yasgui .dl-horizontal dd:after{clear:both}@media (min-width:768px){.yasgui .dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.yasgui .dl-horizontal dd{margin-left:180px}}.yasgui abbr[data-original-title],.yasgui abbr[title]{cursor:help;border-bottom:1px dotted #777}.yasgui .initialism{font-size:90%;text-transform:uppercase}.yasgui blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}.yasgui blockquote ol:last-child,.yasgui blockquote p:last-child,.yasgui blockquote ul:last-child{margin-bottom:0}.yasgui blockquote .small,.yasgui blockquote footer,.yasgui blockquote small{display:block;font-size:80%;line-height:1.42857;color:#777}.yasgui blockquote .small:before,.yasgui blockquote footer:before,.yasgui blockquote small:before{content:'\2014 \00A0'}.yasgui .blockquote-reverse,.yasgui blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}.yasgui .blockquote-reverse .small:before,.yasgui .blockquote-reverse footer:before,.yasgui .blockquote-reverse small:before,.yasgui blockquote.pull-right .small:before,.yasgui blockquote.pull-right footer:before,.yasgui blockquote.pull-right small:before{content:''}.yasgui .blockquote-reverse .small:after,.yasgui .blockquote-reverse footer:after,.yasgui .blockquote-reverse small:after,.yasgui blockquote.pull-right .small:after,.yasgui blockquote.pull-right footer:after,.yasgui blockquote.pull-right small:after{content:'\00A0 \2014'}.yasgui address{margin-bottom:20px;font-style:normal;line-height:1.42857}.yasgui code,.yasgui kbd,.yasgui pre,.yasgui samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}.yasgui code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}.yasgui kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}.yasgui kbd kbd{padding:0;font-size:100%;font-weight:700;box-shadow:none}.yasgui pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}.yasgui pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.yasgui .pre-scrollable{max-height:340px;overflow-y:scroll}.yasgui .container{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.yasgui .container:after,.yasgui .container:before{content:" ";display:table}.yasgui .container:after{clear:both}@media (min-width:768px){.yasgui .container{width:750px}}@media (min-width:992px){.yasgui .container{width:970px}}@media (min-width:1200px){.yasgui .container{width:1170px}}.yasgui .container-fluid{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.yasgui .container-fluid:after,.yasgui .container-fluid:before{content:" ";display:table}.yasgui .container-fluid:after{clear:both}.yasgui .row{margin-left:-15px;margin-right:-15px}.yasgui .row:after,.yasgui .row:before{content:" ";display:table}.yasgui .row:after{clear:both}.yasgui .col-lg-1,.yasgui .col-lg-10,.yasgui .col-lg-11,.yasgui .col-lg-12,.yasgui .col-lg-2,.yasgui .col-lg-3,.yasgui .col-lg-4,.yasgui .col-lg-5,.yasgui .col-lg-6,.yasgui .col-lg-7,.yasgui .col-lg-8,.yasgui .col-lg-9,.yasgui .col-md-1,.yasgui .col-md-10,.yasgui .col-md-11,.yasgui .col-md-12,.yasgui .col-md-2,.yasgui .col-md-3,.yasgui .col-md-4,.yasgui .col-md-5,.yasgui .col-md-6,.yasgui .col-md-7,.yasgui .col-md-8,.yasgui .col-md-9,.yasgui .col-sm-1,.yasgui .col-sm-10,.yasgui .col-sm-11,.yasgui .col-sm-12,.yasgui .col-sm-2,.yasgui .col-sm-3,.yasgui .col-sm-4,.yasgui .col-sm-5,.yasgui .col-sm-6,.yasgui .col-sm-7,.yasgui .col-sm-8,.yasgui .col-sm-9,.yasgui .col-xs-1,.yasgui .col-xs-10,.yasgui .col-xs-11,.yasgui .col-xs-12,.yasgui .col-xs-2,.yasgui .col-xs-3,.yasgui .col-xs-4,.yasgui .col-xs-5,.yasgui .col-xs-6,.yasgui .col-xs-7,.yasgui .col-xs-8,.yasgui .col-xs-9{position:relative;min-height:1px;padding-left:15px;padding-right:15px}.yasgui .col-xs-1,.yasgui .col-xs-10,.yasgui .col-xs-11,.yasgui .col-xs-12,.yasgui .col-xs-2,.yasgui .col-xs-3,.yasgui .col-xs-4,.yasgui .col-xs-5,.yasgui .col-xs-6,.yasgui .col-xs-7,.yasgui .col-xs-8,.yasgui .col-xs-9{float:left}.yasgui .col-xs-1{width:8.33333%}.yasgui .col-xs-2{width:16.66667%}.yasgui .col-xs-3{width:25%}.yasgui .col-xs-4{width:33.33333%}.yasgui .col-xs-5{width:41.66667%}.yasgui .col-xs-6{width:50%}.yasgui .col-xs-7{width:58.33333%}.yasgui .col-xs-8{width:66.66667%}.yasgui .col-xs-9{width:75%}.yasgui .col-xs-10{width:83.33333%}.yasgui .col-xs-11{width:91.66667%}.yasgui .col-xs-12{width:100%}.yasgui .col-xs-pull-0{right:auto}.yasgui .col-xs-pull-1{right:8.33333%}.yasgui .col-xs-pull-2{right:16.66667%}.yasgui .col-xs-pull-3{right:25%}.yasgui .col-xs-pull-4{right:33.33333%}.yasgui .col-xs-pull-5{right:41.66667%}.yasgui .col-xs-pull-6{right:50%}.yasgui .col-xs-pull-7{right:58.33333%}.yasgui .col-xs-pull-8{right:66.66667%}.yasgui .col-xs-pull-9{right:75%}.yasgui .col-xs-pull-10{right:83.33333%}.yasgui .col-xs-pull-11{right:91.66667%}.yasgui .col-xs-pull-12{right:100%}.yasgui .col-xs-push-0{left:auto}.yasgui .col-xs-push-1{left:8.33333%}.yasgui .col-xs-push-2{left:16.66667%}.yasgui .col-xs-push-3{left:25%}.yasgui .col-xs-push-4{left:33.33333%}.yasgui .col-xs-push-5{left:41.66667%}.yasgui .col-xs-push-6{left:50%}.yasgui .col-xs-push-7{left:58.33333%}.yasgui .col-xs-push-8{left:66.66667%}.yasgui .col-xs-push-9{left:75%}.yasgui .col-xs-push-10{left:83.33333%}.yasgui .col-xs-push-11{left:91.66667%}.yasgui .col-xs-push-12{left:100%}.yasgui .col-xs-offset-0{margin-left:0}.yasgui .col-xs-offset-1{margin-left:8.33333%}.yasgui .col-xs-offset-2{margin-left:16.66667%}.yasgui .col-xs-offset-3{margin-left:25%}.yasgui .col-xs-offset-4{margin-left:33.33333%}.yasgui .col-xs-offset-5{margin-left:41.66667%}.yasgui .col-xs-offset-6{margin-left:50%}.yasgui .col-xs-offset-7{margin-left:58.33333%}.yasgui .col-xs-offset-8{margin-left:66.66667%}.yasgui .col-xs-offset-9{margin-left:75%}.yasgui .col-xs-offset-10{margin-left:83.33333%}.yasgui .col-xs-offset-11{margin-left:91.66667%}.yasgui .col-xs-offset-12{margin-left:100%}@media (min-width:768px){.yasgui .col-sm-1,.yasgui .col-sm-10,.yasgui .col-sm-11,.yasgui .col-sm-12,.yasgui .col-sm-2,.yasgui .col-sm-3,.yasgui .col-sm-4,.yasgui .col-sm-5,.yasgui .col-sm-6,.yasgui .col-sm-7,.yasgui .col-sm-8,.yasgui .col-sm-9{float:left}.yasgui .col-sm-1{width:8.33333%}.yasgui .col-sm-2{width:16.66667%}.yasgui .col-sm-3{width:25%}.yasgui .col-sm-4{width:33.33333%}.yasgui .col-sm-5{width:41.66667%}.yasgui .col-sm-6{width:50%}.yasgui .col-sm-7{width:58.33333%}.yasgui .col-sm-8{width:66.66667%}.yasgui .col-sm-9{width:75%}.yasgui .col-sm-10{width:83.33333%}.yasgui .col-sm-11{width:91.66667%}.yasgui .col-sm-12{width:100%}.yasgui .col-sm-pull-0{right:auto}.yasgui .col-sm-pull-1{right:8.33333%}.yasgui .col-sm-pull-2{right:16.66667%}.yasgui .col-sm-pull-3{right:25%}.yasgui .col-sm-pull-4{right:33.33333%}.yasgui .col-sm-pull-5{right:41.66667%}.yasgui .col-sm-pull-6{right:50%}.yasgui .col-sm-pull-7{right:58.33333%}.yasgui .col-sm-pull-8{right:66.66667%}.yasgui .col-sm-pull-9{right:75%}.yasgui .col-sm-pull-10{right:83.33333%}.yasgui .col-sm-pull-11{right:91.66667%}.yasgui .col-sm-pull-12{right:100%}.yasgui .col-sm-push-0{left:auto}.yasgui .col-sm-push-1{left:8.33333%}.yasgui .col-sm-push-2{left:16.66667%}.yasgui .col-sm-push-3{left:25%}.yasgui .col-sm-push-4{left:33.33333%}.yasgui .col-sm-push-5{left:41.66667%}.yasgui .col-sm-push-6{left:50%}.yasgui .col-sm-push-7{left:58.33333%}.yasgui .col-sm-push-8{left:66.66667%}.yasgui .col-sm-push-9{left:75%}.yasgui .col-sm-push-10{left:83.33333%}.yasgui .col-sm-push-11{left:91.66667%}.yasgui .col-sm-push-12{left:100%}.yasgui .col-sm-offset-0{margin-left:0}.yasgui .col-sm-offset-1{margin-left:8.33333%}.yasgui .col-sm-offset-2{margin-left:16.66667%}.yasgui .col-sm-offset-3{margin-left:25%}.yasgui .col-sm-offset-4{margin-left:33.33333%}.yasgui .col-sm-offset-5{margin-left:41.66667%}.yasgui .col-sm-offset-6{margin-left:50%}.yasgui .col-sm-offset-7{margin-left:58.33333%}.yasgui .col-sm-offset-8{margin-left:66.66667%}.yasgui .col-sm-offset-9{margin-left:75%}.yasgui .col-sm-offset-10{margin-left:83.33333%}.yasgui .col-sm-offset-11{margin-left:91.66667%}.yasgui .col-sm-offset-12{margin-left:100%}}@media (min-width:992px){.yasgui .col-md-1,.yasgui .col-md-10,.yasgui .col-md-11,.yasgui .col-md-12,.yasgui .col-md-2,.yasgui .col-md-3,.yasgui .col-md-4,.yasgui .col-md-5,.yasgui .col-md-6,.yasgui .col-md-7,.yasgui .col-md-8,.yasgui .col-md-9{float:left}.yasgui .col-md-1{width:8.33333%}.yasgui .col-md-2{width:16.66667%}.yasgui .col-md-3{width:25%}.yasgui .col-md-4{width:33.33333%}.yasgui .col-md-5{width:41.66667%}.yasgui .col-md-6{width:50%}.yasgui .col-md-7{width:58.33333%}.yasgui .col-md-8{width:66.66667%}.yasgui .col-md-9{width:75%}.yasgui .col-md-10{width:83.33333%}.yasgui .col-md-11{width:91.66667%}.yasgui .col-md-12{width:100%}.yasgui .col-md-pull-0{right:auto}.yasgui .col-md-pull-1{right:8.33333%}.yasgui .col-md-pull-2{right:16.66667%}.yasgui .col-md-pull-3{right:25%}.yasgui .col-md-pull-4{right:33.33333%}.yasgui .col-md-pull-5{right:41.66667%}.yasgui .col-md-pull-6{right:50%}.yasgui .col-md-pull-7{right:58.33333%}.yasgui .col-md-pull-8{right:66.66667%}.yasgui .col-md-pull-9{right:75%}.yasgui .col-md-pull-10{right:83.33333%}.yasgui .col-md-pull-11{right:91.66667%}.yasgui .col-md-pull-12{right:100%}.yasgui .col-md-push-0{left:auto}.yasgui .col-md-push-1{left:8.33333%}.yasgui .col-md-push-2{left:16.66667%}.yasgui .col-md-push-3{left:25%}.yasgui .col-md-push-4{left:33.33333%}.yasgui .col-md-push-5{left:41.66667%}.yasgui .col-md-push-6{left:50%}.yasgui .col-md-push-7{left:58.33333%}.yasgui .col-md-push-8{left:66.66667%}.yasgui .col-md-push-9{left:75%}.yasgui .col-md-push-10{left:83.33333%}.yasgui .col-md-push-11{left:91.66667%}.yasgui .col-md-push-12{left:100%}.yasgui .col-md-offset-0{margin-left:0}.yasgui .col-md-offset-1{margin-left:8.33333%}.yasgui .col-md-offset-2{margin-left:16.66667%}.yasgui .col-md-offset-3{margin-left:25%}.yasgui .col-md-offset-4{margin-left:33.33333%}.yasgui .col-md-offset-5{margin-left:41.66667%}.yasgui .col-md-offset-6{margin-left:50%}.yasgui .col-md-offset-7{margin-left:58.33333%}.yasgui .col-md-offset-8{margin-left:66.66667%}.yasgui .col-md-offset-9{margin-left:75%}.yasgui .col-md-offset-10{margin-left:83.33333%}.yasgui .col-md-offset-11{margin-left:91.66667%}.yasgui .col-md-offset-12{margin-left:100%}}@media (min-width:1200px){.yasgui .col-lg-1,.yasgui .col-lg-10,.yasgui .col-lg-11,.yasgui .col-lg-12,.yasgui .col-lg-2,.yasgui .col-lg-3,.yasgui .col-lg-4,.yasgui .col-lg-5,.yasgui .col-lg-6,.yasgui .col-lg-7,.yasgui .col-lg-8,.yasgui .col-lg-9{float:left}.yasgui .col-lg-1{width:8.33333%}.yasgui .col-lg-2{width:16.66667%}.yasgui .col-lg-3{width:25%}.yasgui .col-lg-4{width:33.33333%}.yasgui .col-lg-5{width:41.66667%}.yasgui .col-lg-6{width:50%}.yasgui .col-lg-7{width:58.33333%}.yasgui .col-lg-8{width:66.66667%}.yasgui .col-lg-9{width:75%}.yasgui .col-lg-10{width:83.33333%}.yasgui .col-lg-11{width:91.66667%}.yasgui .col-lg-12{width:100%}.yasgui .col-lg-pull-0{right:auto}.yasgui .col-lg-pull-1{right:8.33333%}.yasgui .col-lg-pull-2{right:16.66667%}.yasgui .col-lg-pull-3{right:25%}.yasgui .col-lg-pull-4{right:33.33333%}.yasgui .col-lg-pull-5{right:41.66667%}.yasgui .col-lg-pull-6{right:50%}.yasgui .col-lg-pull-7{right:58.33333%}.yasgui .col-lg-pull-8{right:66.66667%}.yasgui .col-lg-pull-9{right:75%}.yasgui .col-lg-pull-10{right:83.33333%}.yasgui .col-lg-pull-11{right:91.66667%}.yasgui .col-lg-pull-12{right:100%}.yasgui .col-lg-push-0{left:auto}.yasgui .col-lg-push-1{left:8.33333%}.yasgui .col-lg-push-2{left:16.66667%}.yasgui .col-lg-push-3{left:25%}.yasgui .col-lg-push-4{left:33.33333%}.yasgui .col-lg-push-5{left:41.66667%}.yasgui .col-lg-push-6{left:50%}.yasgui .col-lg-push-7{left:58.33333%}.yasgui .col-lg-push-8{left:66.66667%}.yasgui .col-lg-push-9{left:75%}.yasgui .col-lg-push-10{left:83.33333%}.yasgui .col-lg-push-11{left:91.66667%}.yasgui .col-lg-push-12{left:100%}.yasgui .col-lg-offset-0{margin-left:0}.yasgui .col-lg-offset-1{margin-left:8.33333%}.yasgui .col-lg-offset-2{margin-left:16.66667%}.yasgui .col-lg-offset-3{margin-left:25%}.yasgui .col-lg-offset-4{margin-left:33.33333%}.yasgui .col-lg-offset-5{margin-left:41.66667%}.yasgui .col-lg-offset-6{margin-left:50%}.yasgui .col-lg-offset-7{margin-left:58.33333%}.yasgui .col-lg-offset-8{margin-left:66.66667%}.yasgui .col-lg-offset-9{margin-left:75%}.yasgui .col-lg-offset-10{margin-left:83.33333%}.yasgui .col-lg-offset-11{margin-left:91.66667%}.yasgui .col-lg-offset-12{margin-left:100%}}.yasgui table{background-color:transparent}.yasgui caption{padding-top:8px;padding-bottom:8px;color:#777;text-align:left}.yasgui th{text-align:left}.yasgui .table{width:100%;max-width:100%;margin-bottom:20px}.yasgui .table>tbody>tr>td,.yasgui .table>tbody>tr>th,.yasgui .table>tfoot>tr>td,.yasgui .table>tfoot>tr>th,.yasgui .table>thead>tr>td,.yasgui .table>thead>tr>th{padding:8px;line-height:1.42857;vertical-align:top;border-top:1px solid #ddd}.yasgui .table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.yasgui .table>caption+thead>tr:first-child>td,.yasgui .table>caption+thead>tr:first-child>th,.yasgui .table>colgroup+thead>tr:first-child>td,.yasgui .table>colgroup+thead>tr:first-child>th,.yasgui .table>thead:first-child>tr:first-child>td,.yasgui .table>thead:first-child>tr:first-child>th{border-top:0}.yasgui .table>tbody+tbody{border-top:2px solid #ddd}.yasgui .table .table{background-color:#fff}.yasgui .table-condensed>tbody>tr>td,.yasgui .table-condensed>tbody>tr>th,.yasgui .table-condensed>tfoot>tr>td,.yasgui .table-condensed>tfoot>tr>th,.yasgui .table-condensed>thead>tr>td,.yasgui .table-condensed>thead>tr>th{padding:5px}.yasgui .table-bordered,.yasgui .table-bordered>tbody>tr>td,.yasgui .table-bordered>tbody>tr>th,.yasgui .table-bordered>tfoot>tr>td,.yasgui .table-bordered>tfoot>tr>th,.yasgui .table-bordered>thead>tr>td,.yasgui .table-bordered>thead>tr>th{border:1px solid #ddd}.yasgui .table-bordered>thead>tr>td,.yasgui .table-bordered>thead>tr>th{border-bottom-width:2px}.yasgui .table-striped>tbody>tr:nth-child(odd){background-color:#f9f9f9}.yasgui .table-hover>tbody>tr:hover{background-color:#f5f5f5}.yasgui table col[class*=col-]{position:static;float:none;display:table-column}.yasgui table td[class*=col-],.yasgui table th[class*=col-]{position:static;float:none;display:table-cell}.yasgui .table>tbody>tr.active>td,.yasgui .table>tbody>tr.active>th,.yasgui .table>tbody>tr>td.active,.yasgui .table>tbody>tr>th.active,.yasgui .table>tfoot>tr.active>td,.yasgui .table>tfoot>tr.active>th,.yasgui .table>tfoot>tr>td.active,.yasgui .table>tfoot>tr>th.active,.yasgui .table>thead>tr.active>td,.yasgui .table>thead>tr.active>th,.yasgui .table>thead>tr>td.active,.yasgui .table>thead>tr>th.active{background-color:#f5f5f5}.yasgui .table-hover>tbody>tr.active:hover>td,.yasgui .table-hover>tbody>tr.active:hover>th,.yasgui .table-hover>tbody>tr:hover>.active,.yasgui .table-hover>tbody>tr>td.active:hover,.yasgui .table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.yasgui .table>tbody>tr.success>td,.yasgui .table>tbody>tr.success>th,.yasgui .table>tbody>tr>td.success,.yasgui .table>tbody>tr>th.success,.yasgui .table>tfoot>tr.success>td,.yasgui .table>tfoot>tr.success>th,.yasgui .table>tfoot>tr>td.success,.yasgui .table>tfoot>tr>th.success,.yasgui .table>thead>tr.success>td,.yasgui .table>thead>tr.success>th,.yasgui .table>thead>tr>td.success,.yasgui .table>thead>tr>th.success{background-color:#dff0d8}.yasgui .table-hover>tbody>tr.success:hover>td,.yasgui .table-hover>tbody>tr.success:hover>th,.yasgui .table-hover>tbody>tr:hover>.success,.yasgui .table-hover>tbody>tr>td.success:hover,.yasgui .table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.yasgui .table>tbody>tr.info>td,.yasgui .table>tbody>tr.info>th,.yasgui .table>tbody>tr>td.info,.yasgui .table>tbody>tr>th.info,.yasgui .table>tfoot>tr.info>td,.yasgui .table>tfoot>tr.info>th,.yasgui .table>tfoot>tr>td.info,.yasgui .table>tfoot>tr>th.info,.yasgui .table>thead>tr.info>td,.yasgui .table>thead>tr.info>th,.yasgui .table>thead>tr>td.info,.yasgui .table>thead>tr>th.info{background-color:#d9edf7}.yasgui .table-hover>tbody>tr.info:hover>td,.yasgui .table-hover>tbody>tr.info:hover>th,.yasgui .table-hover>tbody>tr:hover>.info,.yasgui .table-hover>tbody>tr>td.info:hover,.yasgui .table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.yasgui .table>tbody>tr.warning>td,.yasgui .table>tbody>tr.warning>th,.yasgui .table>tbody>tr>td.warning,.yasgui .table>tbody>tr>th.warning,.yasgui .table>tfoot>tr.warning>td,.yasgui .table>tfoot>tr.warning>th,.yasgui .table>tfoot>tr>td.warning,.yasgui .table>tfoot>tr>th.warning,.yasgui .table>thead>tr.warning>td,.yasgui .table>thead>tr.warning>th,.yasgui .table>thead>tr>td.warning,.yasgui .table>thead>tr>th.warning{background-color:#fcf8e3}.yasgui .table-hover>tbody>tr.warning:hover>td,.yasgui .table-hover>tbody>tr.warning:hover>th,.yasgui .table-hover>tbody>tr:hover>.warning,.yasgui .table-hover>tbody>tr>td.warning:hover,.yasgui .table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.yasgui .table>tbody>tr.danger>td,.yasgui .table>tbody>tr.danger>th,.yasgui .table>tbody>tr>td.danger,.yasgui .table>tbody>tr>th.danger,.yasgui .table>tfoot>tr.danger>td,.yasgui .table>tfoot>tr.danger>th,.yasgui .table>tfoot>tr>td.danger,.yasgui .table>tfoot>tr>th.danger,.yasgui .table>thead>tr.danger>td,.yasgui .table>thead>tr.danger>th,.yasgui .table>thead>tr>td.danger,.yasgui .table>thead>tr>th.danger{background-color:#f2dede}.yasgui .table-hover>tbody>tr.danger:hover>td,.yasgui .table-hover>tbody>tr.danger:hover>th,.yasgui .table-hover>tbody>tr:hover>.danger,.yasgui .table-hover>tbody>tr>td.danger:hover,.yasgui .table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.yasgui .table-responsive{overflow-x:auto;min-height:.01%}@media screen and (max-width:767px){.yasgui .table-responsive{width:100%;margin-bottom:15px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.yasgui .table-responsive>.table{margin-bottom:0}.yasgui .table-responsive>.table>tbody>tr>td,.yasgui .table-responsive>.table>tbody>tr>th,.yasgui .table-responsive>.table>tfoot>tr>td,.yasgui .table-responsive>.table>tfoot>tr>th,.yasgui .table-responsive>.table>thead>tr>td,.yasgui .table-responsive>.table>thead>tr>th{white-space:nowrap}.yasgui .table-responsive>.table-bordered{border:0}.yasgui .table-responsive>.table-bordered>tbody>tr>td:first-child,.yasgui .table-responsive>.table-bordered>tbody>tr>th:first-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>td:first-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>th:first-child,.yasgui .table-responsive>.table-bordered>thead>tr>td:first-child,.yasgui .table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.yasgui .table-responsive>.table-bordered>tbody>tr>td:last-child,.yasgui .table-responsive>.table-bordered>tbody>tr>th:last-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>td:last-child,.yasgui .table-responsive>.table-bordered>tfoot>tr>th:last-child,.yasgui .table-responsive>.table-bordered>thead>tr>td:last-child,.yasgui .table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.yasgui .table-responsive>.table-bordered>tbody>tr:last-child>td,.yasgui .table-responsive>.table-bordered>tbody>tr:last-child>th,.yasgui .table-responsive>.table-bordered>tfoot>tr:last-child>td,.yasgui .table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}.yasgui fieldset{padding:0;margin:0;border:0;min-width:0}.yasgui legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}.yasgui label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}.yasgui input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui input[type=radio],.yasgui input[type=checkbox]{margin:4px 0 0;line-height:normal}.yasgui input[type=file]{display:block}.yasgui input[type=range]{display:block;width:100%}.yasgui select[multiple],.yasgui select[size]{height:auto}.yasgui input[type=radio]:focus,.yasgui input[type=file]:focus,.yasgui input[type=checkbox]:focus{outline:dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.yasgui output{display:block;padding-top:7px;font-size:14px;line-height:1.42857;color:#555}.yasgui .form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.yasgui .form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.yasgui .form-control::-moz-placeholder{color:#999;opacity:1}.yasgui .form-control:-ms-input-placeholder{color:#999}.yasgui .form-control::-webkit-input-placeholder{color:#999}.yasgui .form-control[disabled],.yasgui .form-control[readonly],fieldset[disabled] .yasgui .form-control{cursor:not-allowed;background-color:#eee;opacity:1}.yasgui textarea.form-control{height:auto}.yasgui input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){.yasgui input[type=date],.yasgui input[type=time],.yasgui input[type=datetime-local],.yasgui input[type=month]{line-height:34px}.yasgui .input-group-sm>.input-group-btn>input[type=date].btn,.yasgui .input-group-sm>.input-group-btn>input[type=time].btn,.yasgui .input-group-sm>.input-group-btn>input[type=datetime-local].btn,.yasgui .input-group-sm>.input-group-btn>input[type=month].btn,.yasgui .input-group-sm>input[type=date].form-control,.yasgui .input-group-sm>input[type=date].input-group-addon,.yasgui .input-group-sm>input[type=time].form-control,.yasgui .input-group-sm>input[type=time].input-group-addon,.yasgui .input-group-sm>input[type=datetime-local].form-control,.yasgui .input-group-sm>input[type=datetime-local].input-group-addon,.yasgui .input-group-sm>input[type=month].form-control,.yasgui .input-group-sm>input[type=month].input-group-addon,.yasgui input[type=date].input-sm,.yasgui input[type=time].input-sm,.yasgui input[type=datetime-local].input-sm,.yasgui input[type=month].input-sm{line-height:30px}.yasgui .input-group-lg>.input-group-btn>input[type=date].btn,.yasgui .input-group-lg>.input-group-btn>input[type=time].btn,.yasgui .input-group-lg>.input-group-btn>input[type=datetime-local].btn,.yasgui .input-group-lg>.input-group-btn>input[type=month].btn,.yasgui .input-group-lg>input[type=date].form-control,.yasgui .input-group-lg>input[type=date].input-group-addon,.yasgui .input-group-lg>input[type=time].form-control,.yasgui .input-group-lg>input[type=time].input-group-addon,.yasgui .input-group-lg>input[type=datetime-local].form-control,.yasgui .input-group-lg>input[type=datetime-local].input-group-addon,.yasgui .input-group-lg>input[type=month].form-control,.yasgui .input-group-lg>input[type=month].input-group-addon,.yasgui input[type=date].input-lg,.yasgui input[type=time].input-lg,.yasgui input[type=datetime-local].input-lg,.yasgui input[type=month].input-lg{line-height:46px}}.yasgui .form-group{margin-bottom:15px}.yasgui .checkbox,.yasgui .radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.yasgui .checkbox label,.yasgui .radio label{min-height:20px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.yasgui .checkbox input[type=checkbox],.yasgui .checkbox-inline input[type=checkbox],.yasgui .radio input[type=radio],.yasgui .radio-inline input[type=radio]{position:absolute;margin-left:-20px}.yasgui .checkbox+.checkbox,.yasgui .radio+.radio{margin-top:-5px}.yasgui .checkbox-inline,.yasgui .radio-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.yasgui .checkbox-inline+.checkbox-inline,.yasgui .radio-inline+.radio-inline{margin-top:0;margin-left:10px}.yasgui .checkbox-inline.disabled,.yasgui .checkbox.disabled label,.yasgui .radio-inline.disabled,.yasgui .radio.disabled label,.yasgui input[type=radio].disabled,.yasgui input[type=radio][disabled],.yasgui input[type=checkbox].disabled,.yasgui input[type=checkbox][disabled],fieldset[disabled] .yasgui .checkbox label,fieldset[disabled] .yasgui .checkbox-inline,fieldset[disabled] .yasgui .radio label,fieldset[disabled] .yasgui .radio-inline,fieldset[disabled] .yasgui input[type=radio],fieldset[disabled] .yasgui input[type=checkbox]{cursor:not-allowed}.yasgui .form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.yasgui .form-control-static.input-lg,.yasgui .form-control-static.input-sm,.yasgui .input-group-lg>.form-control-static.form-control,.yasgui .input-group-lg>.form-control-static.input-group-addon,.yasgui .input-group-lg>.input-group-btn>.form-control-static.btn,.yasgui .input-group-sm>.form-control-static.form-control,.yasgui .input-group-sm>.form-control-static.input-group-addon,.yasgui .input-group-sm>.input-group-btn>.form-control-static.btn{padding-left:0;padding-right:0}.yasgui .form-group-sm .form-control,.yasgui .input-group-sm>.form-control,.yasgui .input-group-sm>.input-group-addon,.yasgui .input-group-sm>.input-group-btn>.btn,.yasgui .input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.yasgui .form-group-sm .form-control,.yasgui .input-group-sm>.input-group-btn>select.btn,.yasgui .input-group-sm>select.form-control,.yasgui .input-group-sm>select.input-group-addon,.yasgui select.input-sm{height:30px;line-height:30px}.yasgui .form-group-sm .form-control,.yasgui .input-group-sm>.input-group-btn>select[multiple].btn,.yasgui .input-group-sm>.input-group-btn>textarea.btn,.yasgui .input-group-sm>select[multiple].form-control,.yasgui .input-group-sm>select[multiple].input-group-addon,.yasgui .input-group-sm>textarea.form-control,.yasgui .input-group-sm>textarea.input-group-addon,.yasgui select[multiple].input-sm,.yasgui textarea.input-sm{height:auto}.yasgui .form-group-lg .form-control,.yasgui .input-group-lg>.form-control,.yasgui .input-group-lg>.input-group-addon,.yasgui .input-group-lg>.input-group-btn>.btn,.yasgui .input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.yasgui .form-group-lg .form-control,.yasgui .input-group-lg>.input-group-btn>select.btn,.yasgui .input-group-lg>select.form-control,.yasgui .input-group-lg>select.input-group-addon,.yasgui select.input-lg{height:46px;line-height:46px}.yasgui .form-group-lg .form-control,.yasgui .input-group-lg>.input-group-btn>select[multiple].btn,.yasgui .input-group-lg>.input-group-btn>textarea.btn,.yasgui .input-group-lg>select[multiple].form-control,.yasgui .input-group-lg>select[multiple].input-group-addon,.yasgui .input-group-lg>textarea.form-control,.yasgui .input-group-lg>textarea.input-group-addon,.yasgui select[multiple].input-lg,.yasgui textarea.input-lg{height:auto}.yasgui .has-feedback{position:relative}.yasgui .has-feedback .form-control{padding-right:42.5px}.yasgui .form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center;pointer-events:none}.yasgui .input-group-lg>.form-control+.form-control-feedback,.yasgui .input-group-lg>.input-group-addon+.form-control-feedback,.yasgui .input-group-lg>.input-group-btn>.btn+.form-control-feedback,.yasgui .input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.yasgui .input-group-sm>.form-control+.form-control-feedback,.yasgui .input-group-sm>.input-group-addon+.form-control-feedback,.yasgui .input-group-sm>.input-group-btn>.btn+.form-control-feedback,.yasgui .input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.yasgui .has-success .checkbox,.yasgui .has-success .checkbox-inline,.yasgui .has-success .control-label,.yasgui .has-success .help-block,.yasgui .has-success .radio,.yasgui .has-success .radio-inline,.yasgui .has-success.checkbox label,.yasgui .has-success.checkbox-inline label,.yasgui .has-success.radio label,.yasgui .has-success.radio-inline label{color:#3c763d}.yasgui .has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.yasgui .has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.yasgui .has-success .form-control-feedback{color:#3c763d}.yasgui .has-warning .checkbox,.yasgui .has-warning .checkbox-inline,.yasgui .has-warning .control-label,.yasgui .has-warning .help-block,.yasgui .has-warning .radio,.yasgui .has-warning .radio-inline,.yasgui .has-warning.checkbox label,.yasgui .has-warning.checkbox-inline label,.yasgui .has-warning.radio label,.yasgui .has-warning.radio-inline label{color:#8a6d3b}.yasgui .has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.yasgui .has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.yasgui .has-warning .form-control-feedback{color:#8a6d3b}.yasgui .has-error .checkbox,.yasgui .has-error .checkbox-inline,.yasgui .has-error .control-label,.yasgui .has-error .help-block,.yasgui .has-error .radio,.yasgui .has-error .radio-inline,.yasgui .has-error.checkbox label,.yasgui .has-error.checkbox-inline label,.yasgui .has-error.radio label,.yasgui .has-error.radio-inline label{color:#a94442}.yasgui .has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.yasgui .has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.yasgui .has-error .form-control-feedback{color:#a94442}.yasgui .has-feedback label~.form-control-feedback{top:25px}.yasgui .has-feedback label.sr-only~.form-control-feedback{top:0}.yasgui .help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.yasgui .form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.yasgui .form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.yasgui .form-inline .form-control-static{display:inline-block}.yasgui .form-inline .input-group{display:inline-table;vertical-align:middle}.yasgui .form-inline .input-group .form-control,.yasgui .form-inline .input-group .input-group-addon,.yasgui .form-inline .input-group .input-group-btn{width:auto}.yasgui .form-inline .input-group>.form-control{width:100%}.yasgui .form-inline .control-label{margin-bottom:0;vertical-align:middle}.yasgui .form-inline .checkbox,.yasgui .form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.yasgui .form-inline .checkbox label,.yasgui .form-inline .radio label{padding-left:0}.yasgui .form-inline .checkbox input[type=checkbox],.yasgui .form-inline .radio input[type=radio]{position:relative;margin-left:0}.yasgui .form-inline .has-feedback .form-control-feedback{top:0}}.yasgui .form-horizontal .checkbox,.yasgui .form-horizontal .checkbox-inline,.yasgui .form-horizontal .radio,.yasgui .form-horizontal .radio-inline{margin-top:0;margin-bottom:0;padding-top:7px}.yasgui .form-horizontal .checkbox,.yasgui .form-horizontal .radio{min-height:27px}.yasgui .form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.yasgui .form-horizontal .form-group:after,.yasgui .form-horizontal .form-group:before{content:" ";display:table}.yasgui .form-horizontal .form-group:after{clear:both}@media (min-width:768px){.yasgui .form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}}.yasgui .form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.yasgui .form-horizontal .form-group-lg .control-label{padding-top:14.3px}}@media (min-width:768px){.yasgui .form-horizontal .form-group-sm .control-label{padding-top:6px}}.yasgui .btn{display:inline-block;margin-bottom:0;font-weight:400;text-align:center;vertical-align:middle;touch-action:manipulation;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;padding:6px 12px;font-size:14px;line-height:1.42857;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.yasgui .btn.active.focus,.yasgui .btn.active:focus,.yasgui .btn.focus,.yasgui .btn:active.focus,.yasgui .btn:active:focus,.yasgui .btn:focus{outline:dotted thin;outline:-webkit-focus-ring-color auto 5px;outline-offset:-2px}.yasgui .btn.focus,.yasgui .btn:focus,.yasgui .btn:hover{color:#333;text-decoration:none}.yasgui .btn.active,.yasgui .btn:active{outline:0;background-image:none;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.yasgui .btn.disabled,.yasgui .btn[disabled],fieldset[disabled] .yasgui .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none}.yasgui .btn-default{color:#333;background-color:#fff;border-color:#ccc}.open>.yasgui .btn-default.dropdown-toggle,.yasgui .btn-default.active,.yasgui .btn-default.focus,.yasgui .btn-default:active,.yasgui .btn-default:focus,.yasgui .btn-default:hover{color:#333;background-color:#e6e6e6;border-color:#adadad}.open>.yasgui .btn-default.dropdown-toggle,.yasgui .btn-default.active,.yasgui .btn-default:active{background-image:none}.yasgui .btn-default.disabled,.yasgui .btn-default.disabled.active,.yasgui .btn-default.disabled.focus,.yasgui .btn-default.disabled:active,.yasgui .btn-default.disabled:focus,.yasgui .btn-default.disabled:hover,.yasgui .btn-default[disabled],.yasgui .btn-default[disabled].active,.yasgui .btn-default[disabled].focus,.yasgui .btn-default[disabled]:active,.yasgui .btn-default[disabled]:focus,.yasgui .btn-default[disabled]:hover,fieldset[disabled] .yasgui .btn-default,fieldset[disabled] .yasgui .btn-default.active,fieldset[disabled] .yasgui .btn-default.focus,fieldset[disabled] .yasgui .btn-default:active,fieldset[disabled] .yasgui .btn-default:focus,fieldset[disabled] .yasgui .btn-default:hover{background-color:#fff;border-color:#ccc}.yasgui .btn-default .badge{color:#fff;background-color:#333}.yasgui .btn-primary{color:#fff;background-color:#337ab7;border-color:#2e6da4}.open>.yasgui .btn-primary.dropdown-toggle,.yasgui .btn-primary.active,.yasgui .btn-primary.focus,.yasgui .btn-primary:active,.yasgui .btn-primary:focus,.yasgui .btn-primary:hover{color:#fff;background-color:#286090;border-color:#204d74}.open>.yasgui .btn-primary.dropdown-toggle,.yasgui .btn-primary.active,.yasgui .btn-primary:active{background-image:none}.yasgui .btn-primary.disabled,.yasgui .btn-primary.disabled.active,.yasgui .btn-primary.disabled.focus,.yasgui .btn-primary.disabled:active,.yasgui .btn-primary.disabled:focus,.yasgui .btn-primary.disabled:hover,.yasgui .btn-primary[disabled],.yasgui .btn-primary[disabled].active,.yasgui .btn-primary[disabled].focus,.yasgui .btn-primary[disabled]:active,.yasgui .btn-primary[disabled]:focus,.yasgui .btn-primary[disabled]:hover,fieldset[disabled] .yasgui .btn-primary,fieldset[disabled] .yasgui .btn-primary.active,fieldset[disabled] .yasgui .btn-primary.focus,fieldset[disabled] .yasgui .btn-primary:active,fieldset[disabled] .yasgui .btn-primary:focus,fieldset[disabled] .yasgui .btn-primary:hover{background-color:#337ab7;border-color:#2e6da4}.yasgui .btn-primary .badge{color:#337ab7;background-color:#fff}.yasgui .btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.open>.yasgui .btn-success.dropdown-toggle,.yasgui .btn-success.active,.yasgui .btn-success.focus,.yasgui .btn-success:active,.yasgui .btn-success:focus,.yasgui .btn-success:hover{color:#fff;background-color:#449d44;border-color:#398439}.open>.yasgui .btn-success.dropdown-toggle,.yasgui .btn-success.active,.yasgui .btn-success:active{background-image:none}.yasgui .btn-success.disabled,.yasgui .btn-success.disabled.active,.yasgui .btn-success.disabled.focus,.yasgui .btn-success.disabled:active,.yasgui .btn-success.disabled:focus,.yasgui .btn-success.disabled:hover,.yasgui .btn-success[disabled],.yasgui .btn-success[disabled].active,.yasgui .btn-success[disabled].focus,.yasgui .btn-success[disabled]:active,.yasgui .btn-success[disabled]:focus,.yasgui .btn-success[disabled]:hover,fieldset[disabled] .yasgui .btn-success,fieldset[disabled] .yasgui .btn-success.active,fieldset[disabled] .yasgui .btn-success.focus,fieldset[disabled] .yasgui .btn-success:active,fieldset[disabled] .yasgui .btn-success:focus,fieldset[disabled] .yasgui .btn-success:hover{background-color:#5cb85c;border-color:#4cae4c}.yasgui .btn-success .badge{color:#5cb85c;background-color:#fff}.yasgui .btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.open>.yasgui .btn-info.dropdown-toggle,.yasgui .btn-info.active,.yasgui .btn-info.focus,.yasgui .btn-info:active,.yasgui .btn-info:focus,.yasgui .btn-info:hover{color:#fff;background-color:#31b0d5;border-color:#269abc}.open>.yasgui .btn-info.dropdown-toggle,.yasgui .btn-info.active,.yasgui .btn-info:active{background-image:none}.yasgui .btn-info.disabled,.yasgui .btn-info.disabled.active,.yasgui .btn-info.disabled.focus,.yasgui .btn-info.disabled:active,.yasgui .btn-info.disabled:focus,.yasgui .btn-info.disabled:hover,.yasgui .btn-info[disabled],.yasgui .btn-info[disabled].active,.yasgui .btn-info[disabled].focus,.yasgui .btn-info[disabled]:active,.yasgui .btn-info[disabled]:focus,.yasgui .btn-info[disabled]:hover,fieldset[disabled] .yasgui .btn-info,fieldset[disabled] .yasgui .btn-info.active,fieldset[disabled] .yasgui .btn-info.focus,fieldset[disabled] .yasgui .btn-info:active,fieldset[disabled] .yasgui .btn-info:focus,fieldset[disabled] .yasgui .btn-info:hover{background-color:#5bc0de;border-color:#46b8da}.yasgui .btn-info .badge{color:#5bc0de;background-color:#fff}.yasgui .btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.open>.yasgui .btn-warning.dropdown-toggle,.yasgui .btn-warning.active,.yasgui .btn-warning.focus,.yasgui .btn-warning:active,.yasgui .btn-warning:focus,.yasgui .btn-warning:hover{color:#fff;background-color:#ec971f;border-color:#d58512}.open>.yasgui .btn-warning.dropdown-toggle,.yasgui .btn-warning.active,.yasgui .btn-warning:active{background-image:none}.yasgui .btn-warning.disabled,.yasgui .btn-warning.disabled.active,.yasgui .btn-warning.disabled.focus,.yasgui .btn-warning.disabled:active,.yasgui .btn-warning.disabled:focus,.yasgui .btn-warning.disabled:hover,.yasgui .btn-warning[disabled],.yasgui .btn-warning[disabled].active,.yasgui .btn-warning[disabled].focus,.yasgui .btn-warning[disabled]:active,.yasgui .btn-warning[disabled]:focus,.yasgui .btn-warning[disabled]:hover,fieldset[disabled] .yasgui .btn-warning,fieldset[disabled] .yasgui .btn-warning.active,fieldset[disabled] .yasgui .btn-warning.focus,fieldset[disabled] .yasgui .btn-warning:active,fieldset[disabled] .yasgui .btn-warning:focus,fieldset[disabled] .yasgui .btn-warning:hover{background-color:#f0ad4e;border-color:#eea236}.yasgui .btn-warning .badge{color:#f0ad4e;background-color:#fff}.yasgui .btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.open>.yasgui .btn-danger.dropdown-toggle,.yasgui .btn-danger.active,.yasgui .btn-danger.focus,.yasgui .btn-danger:active,.yasgui .btn-danger:focus,.yasgui .btn-danger:hover{color:#fff;background-color:#c9302c;border-color:#ac2925}.open>.yasgui .btn-danger.dropdown-toggle,.yasgui .btn-danger.active,.yasgui .btn-danger:active{background-image:none}.yasgui .btn-danger.disabled,.yasgui .btn-danger.disabled.active,.yasgui .btn-danger.disabled.focus,.yasgui .btn-danger.disabled:active,.yasgui .btn-danger.disabled:focus,.yasgui .btn-danger.disabled:hover,.yasgui .btn-danger[disabled],.yasgui .btn-danger[disabled].active,.yasgui .btn-danger[disabled].focus,.yasgui .btn-danger[disabled]:active,.yasgui .btn-danger[disabled]:focus,.yasgui .btn-danger[disabled]:hover,fieldset[disabled] .yasgui .btn-danger,fieldset[disabled] .yasgui .btn-danger.active,fieldset[disabled] .yasgui .btn-danger.focus,fieldset[disabled] .yasgui .btn-danger:active,fieldset[disabled] .yasgui .btn-danger:focus,fieldset[disabled] .yasgui .btn-danger:hover{background-color:#d9534f;border-color:#d43f3a}.yasgui .btn-danger .badge{color:#d9534f;background-color:#fff}.yasgui .btn-link{color:#337ab7;font-weight:400;border-radius:0}.yasgui .btn-link,.yasgui .btn-link.active,.yasgui .btn-link:active,.yasgui .btn-link[disabled],fieldset[disabled] .yasgui .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.yasgui .btn-link,.yasgui .btn-link:active,.yasgui .btn-link:focus,.yasgui .btn-link:hover{border-color:transparent}.yasgui .btn-link:focus,.yasgui .btn-link:hover{color:#23527c;text-decoration:underline;background-color:transparent}.yasgui .btn-link[disabled]:focus,.yasgui .btn-link[disabled]:hover,fieldset[disabled] .yasgui .btn-link:focus,fieldset[disabled] .yasgui .btn-link:hover{color:#777;text-decoration:none}.yasgui .btn-group-lg>.btn,.yasgui .btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.yasgui .btn-group-sm>.btn,.yasgui .btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.yasgui .btn-group-xs>.btn,.yasgui .btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.yasgui .btn-block{display:block;width:100%}.yasgui .btn-block+.btn-block{margin-top:5px}.yasgui input[type=button].btn-block,.yasgui input[type=reset].btn-block,.yasgui input[type=submit].btn-block{width:100%}.yasgui .fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.yasgui .fade.in{opacity:1}.yasgui .collapse{display:none;visibility:hidden}.yasgui .collapse.in{display:block;visibility:visible}.yasgui tr.collapse.in{display:table-row}.yasgui tbody.collapse.in{display:table-row-group}.yasgui .collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-property:height,visibility;transition-property:height,visibility;-webkit-transition-duration:.35s;transition-duration:.35s;-webkit-transition-timing-function:ease;transition-timing-function:ease}.yasgui .caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.yasgui .dropdown{position:relative}.yasgui .dropdown-toggle:focus{outline:0}.yasgui .dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;font-size:14px;text-align:left;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175);background-clip:padding-box}.yasgui .dropdown-menu.pull-right{right:0;left:auto}.yasgui .dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.yasgui .dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857;color:#333;white-space:nowrap}.yasgui .dropdown-menu>li>a:focus,.yasgui .dropdown-menu>li>a:hover{text-decoration:none;color:#262626;background-color:#f5f5f5}.yasgui .dropdown-menu>.active>a,.yasgui .dropdown-menu>.active>a:focus,.yasgui .dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;outline:0;background-color:#337ab7}.yasgui .dropdown-menu>.disabled>a,.yasgui .dropdown-menu>.disabled>a:focus,.yasgui .dropdown-menu>.disabled>a:hover{color:#777}.yasgui .dropdown-menu>.disabled>a:focus,.yasgui .dropdown-menu>.disabled>a:hover{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);cursor:not-allowed}.yasgui .open>.dropdown-menu{display:block}.yasgui .open>a{outline:0}.yasgui .dropdown-menu-right{left:auto;right:0}.yasgui .dropdown-menu-left{left:0;right:auto}.yasgui .dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857;color:#777;white-space:nowrap}.yasgui .dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990}.yasgui .pull-right>.dropdown-menu{right:0;left:auto}.yasgui .dropup .caret,.yasgui .navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid;content:""}.yasgui .dropup .dropdown-menu,.yasgui .navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:768px){.yasgui .navbar-right .dropdown-menu{right:0;left:auto}.yasgui .navbar-right .dropdown-menu-left{left:0;right:auto}}.yasgui .btn-group,.yasgui .btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.yasgui .btn-group-vertical>.btn,.yasgui .btn-group>.btn{position:relative;float:left}.yasgui .btn-group-vertical>.btn.active,.yasgui .btn-group-vertical>.btn:active,.yasgui .btn-group-vertical>.btn:focus,.yasgui .btn-group-vertical>.btn:hover,.yasgui .btn-group>.btn.active,.yasgui .btn-group>.btn:active,.yasgui .btn-group>.btn:focus,.yasgui .btn-group>.btn:hover{z-index:2}.yasgui .btn-group .btn+.btn,.yasgui .btn-group .btn+.btn-group,.yasgui .btn-group .btn-group+.btn,.yasgui .btn-group .btn-group+.btn-group{margin-left:-1px}.yasgui .btn-toolbar{margin-left:-5px}.yasgui .btn-toolbar:after,.yasgui .btn-toolbar:before{content:" ";display:table}.yasgui .btn-toolbar:after{clear:both}.yasgui .btn-toolbar .btn-group,.yasgui .btn-toolbar .input-group{float:left}.yasgui .btn-toolbar>.btn,.yasgui .btn-toolbar>.btn-group,.yasgui .btn-toolbar>.input-group{margin-left:5px}.yasgui .btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.yasgui .btn-group>.btn:first-child{margin-left:0}.yasgui .btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.yasgui .btn-group>.btn:last-child:not(:first-child),.yasgui .btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.yasgui .btn-group>.btn-group{float:left}.yasgui .btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.yasgui .btn-group>.btn-group:first-child>.btn:last-child,.yasgui .btn-group>.btn-group:first-child>.dropdown-toggle{border-bottom-right-radius:0;border-top-right-radius:0}.yasgui .btn-group>.btn-group:last-child>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.yasgui .btn-group .dropdown-toggle:active,.yasgui .btn-group.open .dropdown-toggle{outline:0}.yasgui .btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px}.yasgui .btn-group-lg.btn-group>.btn+.dropdown-toggle,.yasgui .btn-group>.btn-lg+.dropdown-toggle{padding-left:12px;padding-right:12px}.yasgui .btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.yasgui .btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.yasgui .btn .caret{margin-left:0}.yasgui .btn-group-lg>.btn .caret,.yasgui .btn-lg .caret{border-width:5px 5px 0}.yasgui .dropup .btn-group-lg>.btn .caret,.yasgui .dropup .btn-lg .caret{border-width:0 5px 5px}.yasgui .btn-group-vertical>.btn,.yasgui .btn-group-vertical>.btn-group,.yasgui .btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.yasgui .btn-group-vertical>.btn-group:after,.yasgui .btn-group-vertical>.btn-group:before{content:" ";display:table}.yasgui .btn-group-vertical>.btn-group:after{clear:both}.yasgui .btn-group-vertical>.btn-group>.btn{float:none}.yasgui .btn-group-vertical>.btn+.btn,.yasgui .btn-group-vertical>.btn+.btn-group,.yasgui .btn-group-vertical>.btn-group+.btn,.yasgui .btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.yasgui .btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.yasgui .btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.yasgui .btn-group-vertical>.btn:last-child:not(:first-child){border-bottom-left-radius:4px;border-top-right-radius:0;border-top-left-radius:0}.yasgui .btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.yasgui .btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.yasgui .btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.yasgui .btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.yasgui .btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.yasgui .btn-group-justified>.btn,.yasgui .btn-group-justified>.btn-group{float:none;display:table-cell;width:1%}.yasgui .btn-group-justified>.btn-group .btn{width:100%}.yasgui .btn-group-justified>.btn-group .dropdown-menu{left:auto}.yasgui [data-toggle=buttons]>.btn input[type=radio],.yasgui [data-toggle=buttons]>.btn input[type=checkbox],.yasgui [data-toggle=buttons]>.btn-group>.btn input[type=radio],.yasgui [data-toggle=buttons]>.btn-group>.btn input[type=checkbox]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.yasgui .input-group{position:relative;display:table;border-collapse:separate}.yasgui .input-group[class*=col-]{float:none;padding-left:0;padding-right:0}.yasgui .input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.yasgui .input-group .form-control,.yasgui .input-group-addon,.yasgui .input-group-btn{display:table-cell}.yasgui .input-group .form-control:not(:first-child):not(:last-child),.yasgui .input-group-addon:not(:first-child):not(:last-child),.yasgui .input-group-btn:not(:first-child):not(:last-child){border-radius:0}.yasgui .input-group-addon,.yasgui .input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.yasgui .input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.yasgui .input-group-addon.input-sm,.yasgui .input-group-sm>.input-group-addon,.yasgui .input-group-sm>.input-group-btn>.input-group-addon.btn{padding:5px 10px;font-size:12px;border-radius:3px}.yasgui .input-group-addon.input-lg,.yasgui .input-group-lg>.input-group-addon,.yasgui .input-group-lg>.input-group-btn>.input-group-addon.btn{padding:10px 16px;font-size:18px;border-radius:6px}.yasgui .input-group-addon input[type=radio],.yasgui .input-group-addon input[type=checkbox]{margin-top:0}.yasgui .input-group .form-control:first-child,.yasgui .input-group-addon:first-child,.yasgui .input-group-btn:first-child>.btn,.yasgui .input-group-btn:first-child>.btn-group>.btn,.yasgui .input-group-btn:first-child>.dropdown-toggle,.yasgui .input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.yasgui .input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.yasgui .input-group-addon:first-child{border-right:0}.yasgui .input-group .form-control:last-child,.yasgui .input-group-addon:last-child,.yasgui .input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.yasgui .input-group-btn:first-child>.btn:not(:first-child),.yasgui .input-group-btn:last-child>.btn,.yasgui .input-group-btn:last-child>.btn-group>.btn,.yasgui .input-group-btn:last-child>.dropdown-toggle{border-bottom-left-radius:0;border-top-left-radius:0}.yasgui .input-group-addon:last-child{border-left:0}.yasgui .input-group-btn{position:relative;font-size:0;white-space:nowrap}.yasgui .input-group-btn>.btn{position:relative}.yasgui .input-group-btn>.btn+.btn{margin-left:-1px}.yasgui .input-group-btn>.btn:active,.yasgui .input-group-btn>.btn:focus,.yasgui .input-group-btn>.btn:hover{z-index:2}.yasgui .input-group-btn:first-child>.btn,.yasgui .input-group-btn:first-child>.btn-group{margin-right:-1px}.yasgui .input-group-btn:last-child>.btn,.yasgui .input-group-btn:last-child>.btn-group{margin-left:-1px}.yasgui .nav{margin-bottom:0;padding-left:0;list-style:none}.yasgui .nav:after,.yasgui .nav:before{content:" ";display:table}.yasgui .nav:after{clear:both}.yasgui .nav>li{position:relative;display:block}.yasgui .nav>li>a{position:relative;display:block;padding:10px 15px}.yasgui .nav>li>a:focus,.yasgui .nav>li>a:hover{text-decoration:none;background-color:#eee}.yasgui .nav>li.disabled>a{color:#777}.yasgui .nav>li.disabled>a:focus,.yasgui .nav>li.disabled>a:hover{color:#777;text-decoration:none;background-color:transparent;cursor:not-allowed}.yasgui .nav .open>a,.yasgui .nav .open>a:focus,.yasgui .nav .open>a:hover{background-color:#eee;border-color:#337ab7}.yasgui .nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.yasgui .nav>li>a>img{max-width:none}.yasgui .nav-tabs{border-bottom:1px solid #ddd}.yasgui .nav-tabs>li{float:left;margin-bottom:-1px}.yasgui .nav-tabs>li>a{margin-right:2px;line-height:1.42857;border:1px solid transparent;border-radius:4px 4px 0 0}.yasgui .nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.yasgui .nav-tabs>li.active>a,.yasgui .nav-tabs>li.active>a:focus,.yasgui .nav-tabs>li.active>a:hover{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default}.yasgui .nav-pills>li{float:left}.yasgui .nav-pills>li>a{border-radius:4px}.yasgui .nav-pills>li+li{margin-left:2px}.yasgui .nav-pills>li.active>a,.yasgui .nav-pills>li.active>a:focus,.yasgui .nav-pills>li.active>a:hover{color:#fff;background-color:#337ab7}.yasgui .nav-stacked>li{float:none}.yasgui .nav-stacked>li+li{margin-top:2px;margin-left:0}.yasgui .nav-justified,.yasgui .nav-tabs.nav-justified{width:100%}.yasgui .nav-justified>li,.yasgui .nav-tabs.nav-justified>li{float:none}.yasgui .nav-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.yasgui .nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.yasgui .nav-justified>li,.yasgui .nav-tabs.nav-justified>li{display:table-cell;width:1%}.yasgui .nav-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{margin-bottom:0}}.yasgui .nav-tabs-justified,.yasgui .nav-tabs.nav-justified{border-bottom:0}.yasgui .nav-tabs-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.yasgui .nav-tabs-justified>.active>a,.yasgui .nav-tabs-justified>.active>a:focus,.yasgui .nav-tabs-justified>.active>a:hover,.yasgui .nav-tabs.nav-justified>.active>a,.yasgui .nav-tabs.nav-justified>.active>a:focus,.yasgui .nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.yasgui .nav-tabs-justified>li>a,.yasgui .nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.yasgui .nav-tabs-justified>.active>a,.yasgui .nav-tabs-justified>.active>a:focus,.yasgui .nav-tabs-justified>.active>a:hover,.yasgui .nav-tabs.nav-justified>.active>a,.yasgui .nav-tabs.nav-justified>.active>a:focus,.yasgui .nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#fff}}.yasgui .tab-content>.tab-pane{display:none;visibility:hidden}.yasgui .tab-content>.active{display:block;visibility:visible}.yasgui .nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.yasgui .navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}.yasgui .navbar:after,.yasgui .navbar:before{content:" ";display:table}.yasgui .navbar:after{clear:both}@media (min-width:768px){.yasgui .navbar{border-radius:4px}}.yasgui .navbar-header:after,.yasgui .navbar-header:before{content:" ";display:table}.yasgui .navbar-header:after{clear:both}@media (min-width:768px){.yasgui .navbar-header{float:left}}.yasgui .navbar-collapse{overflow-x:visible;padding-right:15px;padding-left:15px;border-top:1px solid transparent;box-shadow:inset 0 1px 0 rgba(255,255,255,.1);-webkit-overflow-scrolling:touch}.yasgui .navbar-collapse:after,.yasgui .navbar-collapse:before{content:" ";display:table}.yasgui .navbar-collapse:after{clear:both}.yasgui .navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.yasgui .navbar-collapse{width:auto;border-top:0;box-shadow:none}.yasgui .navbar-collapse.collapse{display:block!important;visibility:visible!important;height:auto!important;padding-bottom:0;overflow:visible!important}.yasgui .navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .yasgui .navbar-collapse,.navbar-fixed-top .yasgui .navbar-collapse,.navbar-static-top .yasgui .navbar-collapse{padding-left:0;padding-right:0}}.yasgui .navbar-fixed-bottom .navbar-collapse,.yasgui .navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.yasgui .navbar-fixed-bottom .navbar-collapse,.yasgui .navbar-fixed-top .navbar-collapse{max-height:200px}}.yasgui .container-fluid>.navbar-collapse,.yasgui .container-fluid>.navbar-header,.yasgui .container>.navbar-collapse,.yasgui .container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.yasgui .container-fluid>.navbar-collapse,.yasgui .container-fluid>.navbar-header,.yasgui .container>.navbar-collapse,.yasgui .container>.navbar-header{margin-right:0;margin-left:0}}.yasgui .navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.yasgui .navbar-static-top{border-radius:0}}.yasgui .navbar-fixed-bottom,.yasgui .navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.yasgui .navbar-fixed-bottom,.yasgui .navbar-fixed-top{border-radius:0}}.yasgui .navbar-fixed-top{top:0;border-width:0 0 1px}.yasgui .navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.yasgui .navbar-brand{float:left;padding:15px;font-size:18px;line-height:20px;height:50px}.yasgui .navbar-brand:focus,.yasgui .navbar-brand:hover{text-decoration:none}.yasgui .navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container .yasgui .navbar-brand,.navbar>.container-fluid .yasgui .navbar-brand{margin-left:-15px}}.yasgui .navbar-toggle{position:relative;float:right;margin-right:15px;padding:9px 10px;margin-top:8px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.yasgui .navbar-toggle:focus{outline:0}.yasgui .navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.yasgui .navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.yasgui .navbar-toggle{display:none}}.yasgui .navbar-nav{margin:7.5px -15px}.yasgui .navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.yasgui .navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.yasgui .navbar-nav .open .dropdown-menu .dropdown-header,.yasgui .navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.yasgui .navbar-nav .open .dropdown-menu>li>a{line-height:20px}.yasgui .navbar-nav .open .dropdown-menu>li>a:focus,.yasgui .navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.yasgui .navbar-nav{float:left;margin:0}.yasgui .navbar-nav>li{float:left}.yasgui .navbar-nav>li>a{padding-top:15px;padding-bottom:15px}}.yasgui .navbar-form{margin:8px -15px;padding:10px 15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.yasgui .navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.yasgui .navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.yasgui .navbar-form .form-control-static{display:inline-block}.yasgui .navbar-form .input-group{display:inline-table;vertical-align:middle}.yasgui .navbar-form .input-group .form-control,.yasgui .navbar-form .input-group .input-group-addon,.yasgui .navbar-form .input-group .input-group-btn{width:auto}.yasgui .navbar-form .input-group>.form-control{width:100%}.yasgui .navbar-form .control-label{margin-bottom:0;vertical-align:middle}.yasgui .navbar-form .checkbox,.yasgui .navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.yasgui .navbar-form .checkbox label,.yasgui .navbar-form .radio label{padding-left:0}.yasgui .navbar-form .checkbox input[type=checkbox],.yasgui .navbar-form .radio input[type=radio]{position:relative;margin-left:0}.yasgui .navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.yasgui .navbar-form .form-group{margin-bottom:5px}.yasgui .navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.yasgui .navbar-form{width:auto;border:0;margin-left:0;margin-right:0;padding-top:0;padding-bottom:0;-webkit-box-shadow:none;box-shadow:none}}.yasgui .navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.yasgui .navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-radius:4px 4px 0 0}.yasgui .navbar-btn{margin-top:8px;margin-bottom:8px}.yasgui .btn-group-sm>.navbar-btn.btn,.yasgui .navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.yasgui .btn-group-xs>.navbar-btn.btn,.yasgui .navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.yasgui .navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.yasgui .navbar-text{float:left;margin-left:15px;margin-right:15px}}@media (min-width:768px){.yasgui .navbar-left{float:left!important}.yasgui .navbar-right{float:right!important;margin-right:-15px}.yasgui .navbar-right~.navbar-right{margin-right:0}}.yasgui .navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.yasgui .navbar-default .navbar-brand{color:#777}.yasgui .navbar-default .navbar-brand:focus,.yasgui .navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.yasgui .navbar-default .navbar-nav>li>a,.yasgui .navbar-default .navbar-text{color:#777}.yasgui .navbar-default .navbar-nav>li>a:focus,.yasgui .navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.yasgui .navbar-default .navbar-nav>.active>a,.yasgui .navbar-default .navbar-nav>.active>a:focus,.yasgui .navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#e7e7e7}.yasgui .navbar-default .navbar-nav>.disabled>a,.yasgui .navbar-default .navbar-nav>.disabled>a:focus,.yasgui .navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.yasgui .navbar-default .navbar-toggle{border-color:#ddd}.yasgui .navbar-default .navbar-toggle:focus,.yasgui .navbar-default .navbar-toggle:hover{background-color:#ddd}.yasgui .navbar-default .navbar-toggle .icon-bar{background-color:#888}.yasgui .navbar-default .navbar-collapse,.yasgui .navbar-default .navbar-form{border-color:#e7e7e7}.yasgui .navbar-default .navbar-nav>.open>a,.yasgui .navbar-default .navbar-nav>.open>a:focus,.yasgui .navbar-default .navbar-nav>.open>a:hover{background-color:#e7e7e7;color:#555}@media (max-width:767px){.yasgui .navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.yasgui .navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.active>a,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#e7e7e7}.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.yasgui .navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.yasgui .navbar-default .navbar-link{color:#777}.yasgui .navbar-default .navbar-link:hover{color:#333}.yasgui .navbar-default .btn-link{color:#777}.yasgui .navbar-default .btn-link:focus,.yasgui .navbar-default .btn-link:hover{color:#333}.yasgui .navbar-default .btn-link[disabled]:focus,.yasgui .navbar-default .btn-link[disabled]:hover,fieldset[disabled] .yasgui .navbar-default .btn-link:focus,fieldset[disabled] .yasgui .navbar-default .btn-link:hover{color:#ccc}.yasgui .navbar-inverse{background-color:#222;border-color:#090909}.yasgui .navbar-inverse .navbar-brand{color:#9d9d9d}.yasgui .navbar-inverse .navbar-brand:focus,.yasgui .navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.yasgui .navbar-inverse .navbar-nav>li>a,.yasgui .navbar-inverse .navbar-text{color:#9d9d9d}.yasgui .navbar-inverse .navbar-nav>li>a:focus,.yasgui .navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.yasgui .navbar-inverse .navbar-nav>.active>a,.yasgui .navbar-inverse .navbar-nav>.active>a:focus,.yasgui .navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#090909}.yasgui .navbar-inverse .navbar-nav>.disabled>a,.yasgui .navbar-inverse .navbar-nav>.disabled>a:focus,.yasgui .navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.yasgui .navbar-inverse .navbar-toggle{border-color:#333}.yasgui .navbar-inverse .navbar-toggle:focus,.yasgui .navbar-inverse .navbar-toggle:hover{background-color:#333}.yasgui .navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.yasgui .navbar-inverse .navbar-collapse,.yasgui .navbar-inverse .navbar-form{border-color:#101010}.yasgui .navbar-inverse .navbar-nav>.open>a,.yasgui .navbar-inverse .navbar-nav>.open>a:focus,.yasgui .navbar-inverse .navbar-nav>.open>a:hover{background-color:#090909;color:#fff}@media (max-width:767px){.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#090909}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#090909}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#090909}.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.yasgui .navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.yasgui .navbar-inverse .navbar-link{color:#9d9d9d}.yasgui .navbar-inverse .navbar-link:hover{color:#fff}.yasgui .navbar-inverse .btn-link{color:#9d9d9d}.yasgui .navbar-inverse .btn-link:focus,.yasgui .navbar-inverse .btn-link:hover{color:#fff}.yasgui .navbar-inverse .btn-link[disabled]:focus,.yasgui .navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .yasgui .navbar-inverse .btn-link:focus,fieldset[disabled] .yasgui .navbar-inverse .btn-link:hover{color:#444}.yasgui .breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.yasgui .breadcrumb>li{display:inline-block}.yasgui .breadcrumb>li+li:before{content:"/\00a0";padding:0 5px;color:#ccc}.yasgui .breadcrumb>.active{color:#777}.yasgui .pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.yasgui .pagination>li{display:inline}.yasgui .pagination>li>a,.yasgui .pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.42857;text-decoration:none;color:#337ab7;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.yasgui .pagination>li:first-child>a,.yasgui .pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.yasgui .pagination>li:last-child>a,.yasgui .pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.yasgui .pagination>li>a:focus,.yasgui .pagination>li>a:hover,.yasgui .pagination>li>span:focus,.yasgui .pagination>li>span:hover{color:#23527c;background-color:#eee;border-color:#ddd}.yasgui .pagination>.active>a,.yasgui .pagination>.active>a:focus,.yasgui .pagination>.active>a:hover,.yasgui .pagination>.active>span,.yasgui .pagination>.active>span:focus,.yasgui .pagination>.active>span:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7;cursor:default}.yasgui .pagination>.disabled>a,.yasgui .pagination>.disabled>a:focus,.yasgui .pagination>.disabled>a:hover,.yasgui .pagination>.disabled>span,.yasgui .pagination>.disabled>span:focus,.yasgui .pagination>.disabled>span:hover{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.yasgui .pagination-lg>li>a,.yasgui .pagination-lg>li>span{padding:10px 16px;font-size:18px}.yasgui .pagination-lg>li:first-child>a,.yasgui .pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.yasgui .pagination-lg>li:last-child>a,.yasgui .pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.yasgui .pagination-sm>li>a,.yasgui .pagination-sm>li>span{padding:5px 10px;font-size:12px}.yasgui .pagination-sm>li:first-child>a,.yasgui .pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.yasgui .pagination-sm>li:last-child>a,.yasgui .pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.yasgui .pager{padding-left:0;margin:20px 0;list-style:none;text-align:center}.yasgui .pager:after,.yasgui .pager:before{content:" ";display:table}.yasgui .pager:after{clear:both}.yasgui .pager li{display:inline}.yasgui .pager li>a,.yasgui .pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.yasgui .pager li>a:focus,.yasgui .pager li>a:hover{text-decoration:none;background-color:#eee}.yasgui .pager .next>a,.yasgui .pager .next>span{float:right}.yasgui .pager .previous>a,.yasgui .pager .previous>span{float:left}.yasgui .pager .disabled>a,.yasgui .pager .disabled>a:focus,.yasgui .pager .disabled>a:hover,.yasgui .pager .disabled>span{color:#777;background-color:#fff;cursor:not-allowed}.yasgui .label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.yasgui .label:empty{display:none}.btn .yasgui .label{position:relative;top:-1px}.yasgui a.label:focus,.yasgui a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.yasgui .label-default{background-color:#777}.yasgui .label-default[href]:focus,.yasgui .label-default[href]:hover{background-color:#5e5e5e}.yasgui .label-primary{background-color:#337ab7}.yasgui .label-primary[href]:focus,.yasgui .label-primary[href]:hover{background-color:#286090}.yasgui .label-success{background-color:#5cb85c}.yasgui .label-success[href]:focus,.yasgui .label-success[href]:hover{background-color:#449d44}.yasgui .label-info{background-color:#5bc0de}.yasgui .label-info[href]:focus,.yasgui .label-info[href]:hover{background-color:#31b0d5}.yasgui .label-warning{background-color:#f0ad4e}.yasgui .label-warning[href]:focus,.yasgui .label-warning[href]:hover{background-color:#ec971f}.yasgui .label-danger{background-color:#d9534f}.yasgui .label-danger[href]:focus,.yasgui .label-danger[href]:hover{background-color:#c9302c}.yasgui .badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;color:#fff;line-height:1;vertical-align:baseline;white-space:nowrap;text-align:center;background-color:#777;border-radius:10px}.yasgui .badge:empty{display:none}.btn .yasgui .badge{position:relative;top:-1px}.btn-xs .yasgui .badge,.yasgui .btn-group-xs>.btn .yasgui .badge{top:0;padding:1px 5px}.list-group-item.active>.yasgui .badge,.nav-pills>.active>a>.yasgui .badge{color:#337ab7;background-color:#fff}.list-group-item>.yasgui .badge{float:right}.list-group-item>.yasgui .badge+.yasgui .badge{margin-right:5px}.nav-pills>li>a>.yasgui .badge{margin-left:3px}.yasgui a.badge:focus,.yasgui a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.yasgui .jumbotron{padding:30px 15px;margin-bottom:30px;color:inherit;background-color:#eee}.yasgui .jumbotron .h1,.yasgui .jumbotron h1{color:inherit}.yasgui .jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.yasgui .jumbotron>hr{border-top-color:#d5d5d5}.container .yasgui .jumbotron,.container-fluid .yasgui .jumbotron{border-radius:6px}.yasgui .jumbotron .container{max-width:100%}@media screen and (min-width:768px){.yasgui .jumbotron{padding:48px 0}.container .yasgui .jumbotron,.container-fluid .yasgui .jumbotron{padding-left:60px;padding-right:60px}.yasgui .jumbotron .h1,.yasgui .jumbotron h1{font-size:63px}}.yasgui .thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;-o-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.yasgui .thumbnail a>img,.yasgui .thumbnail>img{display:block;max-width:100%;height:auto;margin-left:auto;margin-right:auto}.yasgui .thumbnail .caption{padding:9px;color:#333}.yasgui a.thumbnail.active,.yasgui a.thumbnail:focus,.yasgui a.thumbnail:hover{border-color:#337ab7}.yasgui .alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.yasgui .alert h4{margin-top:0;color:inherit}.yasgui .alert .alert-link{font-weight:700}.yasgui .alert>p,.yasgui .alert>ul{margin-bottom:0}.yasgui .alert>p+p{margin-top:5px}.yasgui .alert-dismissable,.yasgui .alert-dismissible{padding-right:35px}.yasgui .alert-dismissable .close,.yasgui .alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.yasgui .alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#3c763d}.yasgui .alert-success hr{border-top-color:#c9e2b3}.yasgui .alert-success .alert-link{color:#2b542c}.yasgui .alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#31708f}.yasgui .alert-info hr{border-top-color:#a6e1ec}.yasgui .alert-info .alert-link{color:#245269}.yasgui .alert-warning{background-color:#fcf8e3;border-color:#faebcc;color:#8a6d3b}.yasgui .alert-warning hr{border-top-color:#f7e1b5}.yasgui .alert-warning .alert-link{color:#66512c}.yasgui .alert-danger{background-color:#f2dede;border-color:#ebccd1;color:#a94442}.yasgui .alert-danger hr{border-top-color:#e4b9c0}.yasgui .alert-danger .alert-link{color:#843534}.yasgui .progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.yasgui .progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#337ab7;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.yasgui .progress-bar-striped,.yasgui .progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:40px 40px}.yasgui .progress-bar.active,.yasgui .progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.yasgui .progress-bar-success{background-color:#5cb85c}.progress-striped .yasgui .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .progress-bar-info{background-color:#5bc0de}.progress-striped .yasgui .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .progress-bar-warning{background-color:#f0ad4e}.progress-striped .yasgui .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .progress-bar-danger{background-color:#d9534f}.progress-striped .yasgui .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.yasgui .media{margin-top:15px}.yasgui .media:first-child{margin-top:0}.yasgui .media-right,.yasgui .media>.pull-right{padding-left:10px}.yasgui .media-left,.yasgui .media>.pull-left{padding-right:10px}.yasgui .media-body,.yasgui .media-left,.yasgui .media-right{display:table-cell;vertical-align:top}.yasgui .media-middle{vertical-align:middle}.yasgui .media-bottom{vertical-align:bottom}.yasgui .media-heading{margin-top:0;margin-bottom:5px}.yasgui .media-list{padding-left:0;list-style:none}.yasgui .list-group{margin-bottom:20px;padding-left:0}.yasgui .list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.yasgui .list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.yasgui .list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.yasgui a.list-group-item{color:#555}.yasgui a.list-group-item .list-group-item-heading{color:#333}.yasgui a.list-group-item:focus,.yasgui a.list-group-item:hover{text-decoration:none;color:#555;background-color:#f5f5f5}.yasgui .list-group-item.disabled,.yasgui .list-group-item.disabled:focus,.yasgui .list-group-item.disabled:hover{background-color:#eee;color:#777;cursor:not-allowed}.yasgui .list-group-item.disabled .list-group-item-heading,.yasgui .list-group-item.disabled:focus .list-group-item-heading,.yasgui .list-group-item.disabled:hover .list-group-item-heading{color:inherit}.yasgui .list-group-item.disabled .list-group-item-text,.yasgui .list-group-item.disabled:focus .list-group-item-text,.yasgui .list-group-item.disabled:hover .list-group-item-text{color:#777}.yasgui .list-group-item.active,.yasgui .list-group-item.active:focus,.yasgui .list-group-item.active:hover{z-index:2;color:#fff;background-color:#337ab7;border-color:#337ab7}.yasgui .list-group-item.active .list-group-item-heading,.yasgui .list-group-item.active .list-group-item-heading>.small,.yasgui .list-group-item.active .list-group-item-heading>small,.yasgui .list-group-item.active:focus .list-group-item-heading,.yasgui .list-group-item.active:focus .list-group-item-heading>.small,.yasgui .list-group-item.active:focus .list-group-item-heading>small,.yasgui .list-group-item.active:hover .list-group-item-heading,.yasgui .list-group-item.active:hover .list-group-item-heading>.small,.yasgui .list-group-item.active:hover .list-group-item-heading>small{color:inherit}.yasgui .list-group-item.active .list-group-item-text,.yasgui .list-group-item.active:focus .list-group-item-text,.yasgui .list-group-item.active:hover .list-group-item-text{color:#c7ddef}.yasgui .list-group-item-success{color:#3c763d;background-color:#dff0d8}.yasgui a.list-group-item-success{color:#3c763d}.yasgui a.list-group-item-success .list-group-item-heading{color:inherit}.yasgui a.list-group-item-success:focus,.yasgui a.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}.yasgui a.list-group-item-success.active,.yasgui a.list-group-item-success.active:focus,.yasgui a.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.yasgui .list-group-item-info{color:#31708f;background-color:#d9edf7}.yasgui a.list-group-item-info{color:#31708f}.yasgui a.list-group-item-info .list-group-item-heading{color:inherit}.yasgui a.list-group-item-info:focus,.yasgui a.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}.yasgui a.list-group-item-info.active,.yasgui a.list-group-item-info.active:focus,.yasgui a.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.yasgui .list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}.yasgui a.list-group-item-warning{color:#8a6d3b}.yasgui a.list-group-item-warning .list-group-item-heading{color:inherit}.yasgui a.list-group-item-warning:focus,.yasgui a.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}.yasgui a.list-group-item-warning.active,.yasgui a.list-group-item-warning.active:focus,.yasgui a.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.yasgui .list-group-item-danger{color:#a94442;background-color:#f2dede}.yasgui a.list-group-item-danger{color:#a94442}.yasgui a.list-group-item-danger .list-group-item-heading{color:inherit}.yasgui a.list-group-item-danger:focus,.yasgui a.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}.yasgui a.list-group-item-danger.active,.yasgui a.list-group-item-danger.active:focus,.yasgui a.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.yasgui .list-group-item-heading{margin-top:0;margin-bottom:5px}.yasgui .list-group-item-text{margin-bottom:0;line-height:1.3}.yasgui .panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.yasgui .panel-body{padding:15px}.yasgui .panel-body:after,.yasgui .panel-body:before{content:" ";display:table}.yasgui .panel-body:after{clear:both}.yasgui .panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.yasgui .panel-heading>.dropdown .dropdown-toggle{color:inherit}.yasgui .panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.yasgui .panel-title>a{color:inherit}.yasgui .panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.yasgui .panel>.list-group,.yasgui .panel>.panel-collapse>.list-group{margin-bottom:0}.yasgui .panel>.list-group .list-group-item,.yasgui .panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.yasgui .panel>.list-group:first-child .list-group-item:first-child,.yasgui .panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-right-radius:3px;border-top-left-radius:3px}.yasgui .panel>.list-group:last-child .list-group-item:last-child,.yasgui .panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.yasgui .list-group+.panel-footer,.yasgui .panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.yasgui .panel>.panel-collapse>.table,.yasgui .panel>.table,.yasgui .panel>.table-responsive>.table{margin-bottom:0}.yasgui .panel>.panel-collapse>.table caption,.yasgui .panel>.table caption,.yasgui .panel>.table-responsive>.table caption{padding-left:15px;padding-right:15px}.yasgui .panel>.table-responsive:first-child>.table:first-child,.yasgui .panel>.table:first-child{border-top-right-radius:3px;border-top-left-radius:3px}.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.yasgui .panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.yasgui .panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.yasgui .panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child,.yasgui .panel>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-left-radius:3px;border-bottom-right-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.yasgui .panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.yasgui .panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.yasgui .panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.yasgui .panel>.panel-body+.table,.yasgui .panel>.panel-body+.table-responsive,.yasgui .panel>.table+.panel-body,.yasgui .panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.yasgui .panel>.table>tbody:first-child>tr:first-child td,.yasgui .panel>.table>tbody:first-child>tr:first-child th{border-top:0}.yasgui .panel>.table-bordered,.yasgui .panel>.table-responsive>.table-bordered{border:0}.yasgui .panel>.table-bordered>tbody>tr>td:first-child,.yasgui .panel>.table-bordered>tbody>tr>th:first-child,.yasgui .panel>.table-bordered>tfoot>tr>td:first-child,.yasgui .panel>.table-bordered>tfoot>tr>th:first-child,.yasgui .panel>.table-bordered>thead>tr>td:first-child,.yasgui .panel>.table-bordered>thead>tr>th:first-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.yasgui .panel>.table-bordered>tbody>tr>td:last-child,.yasgui .panel>.table-bordered>tbody>tr>th:last-child,.yasgui .panel>.table-bordered>tfoot>tr>td:last-child,.yasgui .panel>.table-bordered>tfoot>tr>th:last-child,.yasgui .panel>.table-bordered>thead>tr>td:last-child,.yasgui .panel>.table-bordered>thead>tr>th:last-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.yasgui .panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.yasgui .panel>.table-bordered>tbody>tr:first-child>td,.yasgui .panel>.table-bordered>tbody>tr:first-child>th,.yasgui .panel>.table-bordered>tbody>tr:last-child>td,.yasgui .panel>.table-bordered>tbody>tr:last-child>th,.yasgui .panel>.table-bordered>tfoot>tr:last-child>td,.yasgui .panel>.table-bordered>tfoot>tr:last-child>th,.yasgui .panel>.table-bordered>thead>tr:first-child>td,.yasgui .panel>.table-bordered>thead>tr:first-child>th,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.yasgui .panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.yasgui .panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th,.yasgui .panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.yasgui .panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.yasgui .panel>.table-responsive{border:0;margin-bottom:0}.yasgui .panel-group{margin-bottom:20px}.yasgui .panel-group .panel{margin-bottom:0;border-radius:4px}.yasgui .panel-group .panel+.panel{margin-top:5px}.yasgui .panel-group .panel-heading{border-bottom:0}.yasgui .panel-group .panel-heading+.panel-collapse>.list-group,.yasgui .panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.yasgui .panel-group .panel-footer{border-top:0}.yasgui .panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.yasgui .panel-default{border-color:#ddd}.yasgui .panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.yasgui .panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.yasgui .panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.yasgui .panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.yasgui .panel-primary{border-color:#337ab7}.yasgui .panel-primary>.panel-heading{color:#fff;background-color:#337ab7;border-color:#337ab7}.yasgui .panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#337ab7}.yasgui .panel-primary>.panel-heading .badge{color:#337ab7;background-color:#fff}.yasgui .panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#337ab7}.yasgui .panel-success{border-color:#d6e9c6}.yasgui .panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.yasgui .panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.yasgui .panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.yasgui .panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.yasgui .panel-info{border-color:#bce8f1}.yasgui .panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.yasgui .panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.yasgui .panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.yasgui .panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.yasgui .panel-warning{border-color:#faebcc}.yasgui .panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.yasgui .panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.yasgui .panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.yasgui .panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.yasgui .panel-danger{border-color:#ebccd1}.yasgui .panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.yasgui .panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.yasgui .panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.yasgui .panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.yasgui .embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.yasgui .embed-responsive .embed-responsive-item,.yasgui .embed-responsive embed,.yasgui .embed-responsive iframe,.yasgui .embed-responsive object,.yasgui .embed-responsive video{position:absolute;top:0;left:0;bottom:0;height:100%;width:100%;border:0}.yasgui .embed-responsive.embed-responsive-16by9{padding-bottom:56.25%}.yasgui .embed-responsive.embed-responsive-4by3{padding-bottom:75%}.yasgui .well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.yasgui .well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.yasgui .well-lg{padding:24px;border-radius:6px}.yasgui .well-sm{padding:9px;border-radius:3px}.yasgui .close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.yasgui .close:focus,.yasgui .close:hover{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}.yasgui button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.yasgui .modal-open{overflow:hidden}.yasgui .modal{display:none;overflow:hidden;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;-webkit-overflow-scrolling:touch;outline:0}.yasgui .modal.fade .modal-dialog{-webkit-transform:translate(0,-25%);-ms-transform:translate(0,-25%);-o-transform:translate(0,-25%);transform:translate(0,-25%);-webkit-transition:-webkit-transform .3s ease-out;-moz-transition:-moz-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.yasgui .modal.in .modal-dialog{-webkit-transform:translate(0,0);-ms-transform:translate(0,0);-o-transform:translate(0,0);transform:translate(0,0)}.yasgui .modal-open .modal{overflow-x:hidden;overflow-y:auto}.yasgui .modal-dialog{position:relative;width:auto;margin:10px}.yasgui .modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.yasgui .modal-backdrop{position:absolute;top:0;right:0;left:0;background-color:#000}.yasgui .modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.yasgui .modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.yasgui .modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.43px}.yasgui .modal-header .close{margin-top:-2px}.yasgui .modal-title{margin:0;line-height:1.42857}.yasgui .modal-body{position:relative;padding:15px}.yasgui .modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.yasgui .modal-footer:after,.yasgui .modal-footer:before{content:" ";display:table}.yasgui .modal-footer:after{clear:both}.yasgui .modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.yasgui .modal-footer .btn-group .btn+.btn{margin-left:-1px}.yasgui .modal-footer .btn-block+.btn-block{margin-left:0}.yasgui .modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.yasgui .modal-dialog{width:600px;margin:30px auto}.yasgui .modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.yasgui .modal-sm{width:300px}}@media (min-width:992px){.yasgui .modal-lg{width:900px}}.yasgui .tooltip{position:absolute;z-index:1070;display:block;visibility:visible;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:12px;font-weight:400;line-height:1.4;opacity:0;filter:alpha(opacity=0)}.yasgui .tooltip.in{opacity:.9;filter:alpha(opacity=90)}.yasgui .tooltip.top{margin-top:-3px;padding:5px 0}.yasgui .tooltip.right{margin-left:3px;padding:0 5px}.yasgui .tooltip.bottom{margin-top:3px;padding:5px 0}.yasgui .tooltip.left{margin-left:-3px;padding:0 5px}.yasgui .tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.yasgui .tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.yasgui .tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.yasgui .tooltip.top-left .tooltip-arrow{bottom:0;right:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.yasgui .tooltip.top-right .tooltip-arrow{bottom:0;left:5px;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.yasgui .tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.yasgui .tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.yasgui .tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.yasgui .tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.yasgui .tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.yasgui .popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;line-height:1.42857;text-align:left;background-color:#fff;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);white-space:normal}.yasgui .popover.top{margin-top:-10px}.yasgui .popover.right{margin-left:10px}.yasgui .popover.bottom{margin-top:10px}.yasgui .popover.left{margin-left:-10px}.yasgui .popover-title{margin:0;padding:8px 14px;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.yasgui .popover-content{padding:9px 14px}.yasgui .popover>.arrow,.yasgui .popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.yasgui .popover>.arrow{border-width:11px}.yasgui .popover>.arrow:after{border-width:10px;content:""}.yasgui .popover.top>.arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px}.yasgui .popover.top>.arrow:after{content:" ";bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#fff}.yasgui .popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25)}.yasgui .popover.right>.arrow:after{content:" ";left:1px;bottom:-10px;border-left-width:0;border-right-color:#fff}.yasgui .popover.bottom>.arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);top:-11px}.yasgui .popover.bottom>.arrow:after{content:" ";top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.yasgui .popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.yasgui .popover.left>.arrow:after{content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-10px}.yasgui .carousel{position:relative}.yasgui .carousel-inner{position:relative;overflow:hidden;width:100%}.yasgui .carousel-inner>.item{display:none;position:relative;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.yasgui .carousel-inner>.item>a>img,.yasgui .carousel-inner>.item>img{display:block;max-width:100%;height:auto;line-height:1}@media all and (transform-3d),(-webkit-transform-3d){.yasgui .carousel-inner>.item{transition:transform .6s ease-in-out;backface-visibility:hidden;perspective:1000}.yasgui .carousel-inner>.item.active.right,.yasgui .carousel-inner>.item.next{transform:translate3d(100%,0,0);left:0}.yasgui .carousel-inner>.item.active.left,.yasgui .carousel-inner>.item.prev{transform:translate3d(-100%,0,0);left:0}.yasgui .carousel-inner>.item.active,.yasgui .carousel-inner>.item.next.left,.yasgui .carousel-inner>.item.prev.right{transform:translate3d(0,0,0);left:0}}.yasgui .carousel-inner>.active,.yasgui .carousel-inner>.next,.yasgui .carousel-inner>.prev{display:block}.yasgui .carousel-inner>.active{left:0}.yasgui .carousel-inner>.next,.yasgui .carousel-inner>.prev{position:absolute;top:0;width:100%}.yasgui .carousel-inner>.next{left:100%}.yasgui .carousel-inner>.prev{left:-100%}.yasgui .carousel-inner>.next.left,.yasgui .carousel-inner>.prev.right{left:0}.yasgui .carousel-inner>.active.left{left:-100%}.yasgui .carousel-inner>.active.right{left:100%}.yasgui .carousel-control{position:absolute;top:0;left:0;bottom:0;width:15%;opacity:.5;filter:alpha(opacity=50);font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.yasgui .carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1)}.yasgui .carousel-control.right{left:auto;right:0;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1)}.yasgui .carousel-control:focus,.yasgui .carousel-control:hover{outline:0;color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next,.yasgui .carousel-control .icon-prev{position:absolute;top:50%;z-index:5;display:inline-block}.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .icon-prev{left:50%;margin-left:-10px}.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next{right:50%;margin-right:-10px}.yasgui .carousel-control .icon-next,.yasgui .carousel-control .icon-prev{width:20px;height:20px;margin-top:-10px;font-family:serif}.yasgui .carousel-control .icon-prev:before{content:'\2039'}.yasgui .carousel-control .icon-next:before{content:'\203a'}.yasgui .carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;margin-left:-30%;padding-left:0;list-style:none;text-align:center}.yasgui .carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;border:1px solid #fff;border-radius:10px;cursor:pointer;background-color:transparent}.yasgui .carousel-indicators .active{margin:0;width:12px;height:12px;background-color:#fff}.yasgui .carousel-caption{position:absolute;left:15%;right:15%;bottom:20px;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.yasgui .carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next,.yasgui .carousel-control .icon-prev{width:30px;height:30px;margin-top:-15px;font-size:30px}.yasgui .carousel-control .glyphicon-chevron-left,.yasgui .carousel-control .icon-prev{margin-left:-15px}.yasgui .carousel-control .glyphicon-chevron-right,.yasgui .carousel-control .icon-next{margin-right:-15px}.yasgui .carousel-caption{left:20%;right:20%;padding-bottom:30px}.yasgui .carousel-indicators{bottom:20px}}.yasgui .clearfix:after,.yasgui .clearfix:before{content:" ";display:table}.yasgui .clearfix:after{clear:both}.yasgui .center-block{display:block;margin-left:auto;margin-right:auto}.yasgui .pull-right{float:right!important}.yasgui .pull-left{float:left!important}.yasgui .hide{display:none!important}.yasgui .show{display:block!important}.yasgui .invisible{visibility:hidden}.yasgui .text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.yasgui .hidden{display:none!important;visibility:hidden!important}.yasgui .affix{position:fixed}.yasgui .visible-lg,.yasgui .visible-lg-block,.yasgui .visible-lg-inline,.yasgui .visible-lg-inline-block,.yasgui .visible-md,.yasgui .visible-md-block,.yasgui .visible-md-inline,.yasgui .visible-md-inline-block,.yasgui .visible-print,.yasgui .visible-print-block,.yasgui .visible-print-inline,.yasgui .visible-print-inline-block,.yasgui .visible-sm,.yasgui .visible-sm-block,.yasgui .visible-sm-inline,.yasgui .visible-sm-inline-block,.yasgui .visible-xs,.yasgui .visible-xs-block,.yasgui .visible-xs-inline,.yasgui .visible-xs-inline-block{display:none!important}@media (max-width:767px){.yasgui .visible-xs{display:block!important}.yasgui table.visible-xs{display:table}.yasgui tr.visible-xs{display:table-row!important}.yasgui td.visible-xs,.yasgui th.visible-xs{display:table-cell!important}}@media (max-width:767px){.yasgui .visible-xs-block{display:block!important}}@media (max-width:767px){.yasgui .visible-xs-inline{display:inline!important}}@media (max-width:767px){.yasgui .visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm{display:block!important}.yasgui table.visible-sm{display:table}.yasgui tr.visible-sm{display:table-row!important}.yasgui td.visible-sm,.yasgui th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.yasgui .visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md{display:block!important}.yasgui table.visible-md{display:table}.yasgui tr.visible-md{display:table-row!important}.yasgui td.visible-md,.yasgui th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.yasgui .visible-lg{display:block!important}.yasgui table.visible-lg{display:table}.yasgui tr.visible-lg{display:table-row!important}.yasgui td.visible-lg,.yasgui th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.yasgui .visible-lg-block{display:block!important}}@media (min-width:1200px){.yasgui .visible-lg-inline{display:inline!important}}@media (min-width:1200px){.yasgui .visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.yasgui .hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.yasgui .hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.yasgui .hidden-md{display:none!important}}@media (min-width:1200px){.yasgui .hidden-lg{display:none!important}}@media print{.yasgui .visible-print{display:block!important}.yasgui table.visible-print{display:table}.yasgui tr.visible-print{display:table-row!important}.yasgui td.visible-print,.yasgui th.visible-print{display:table-cell!important}}@media print{.yasgui .visible-print-block{display:block!important}}@media print{.yasgui .visible-print-inline{display:inline!important}}@media print{.yasgui .visible-print-inline-block{display:inline-block!important}}@media print{.yasgui .hidden-print{display:none!important}}.yasgui .yasqe .CodeMirror,.yasgui .yasr .CodeMirror{border-color:#ddd}.yasgui .nav-tabs li.tab-sortable-highlight{border:3px dashed #ddd;border-bottom:0}.yasgui .nav-tabs li a[role=addTab]{padding:0;margin:4px 0;cursor:pointer;font-weight:700;font-size:21px;background-color:transparent;border-color:transparent}.yasgui .nav-tabs li .close{margin-left:7px;font-size:17px}.yasgui .nav-tabs li a{display:inline-block}.yasgui .nav-tabs li div{color:#555;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default;padding:10px 15px;display:none}.yasgui .nav-tabs li.rename a{display:none}.yasgui .nav-tabs li.rename div{display:inline-block}.yasgui .menu-slide{position:absolute;border:1px solid #ddd;border-top:0;top:0;left:0;z-index:100;visibility:hidden;width:600px;height:auto;background:#f5f5f5;-webkit-transition:all .5s;transition:all .5s;-webkit-perspective:1500px;perspective:1500px;-webkit-perspective-origin:0 50%;perspective-origin:0 50%;-webkit-transform:translate3d(-100%,0,0) rotateY(90deg);transform:translate3d(-100%,0,0) rotateY(90deg);-webkit-transform-origin:100% 50%;transform-origin:100% 50%;-webkit-transform-style:preserve-3d;transform-style:preserve-3d}.yasgui .menu-slide .yasguiLogo{cursor:pointer;float:right;margin:5px}.yasgui .menu-slide::after{display:none}.yasgui .menu-slide .tab-pane,.yasgui .menu-slide .tabPaneMenuTabs{margin:10px}.yasgui .menu-slide .logo{margin-left:auto;margin-right:0}.yasgui .menu-slide .requestConfig .textInputsRow:first-child .close{display:none}.yasgui .menu-slide .requestConfig .close{font-size:18px}.yasgui .menu-slide .requestConfig .textInputsRow *{margin:5px 3px 0 0}.yasgui .menu-slide .requestConfig .row{display:table;margin:5px 0}.yasgui .menu-slide .requestConfig label{font-size:80%}.yasgui .menu-slide .requestConfig .rowLabel{font-weight:700}.yasgui .menu-slide .requestConfig [class*=col-]{float:none;display:table-cell;vertical-align:middle;padding:5px}.yasgui .tab-pane.menu-open{-webkit-perspective:1500px;perspective:1500px;-webkit-perspective-origin:0 50%;perspective-origin:0 50%}.yasgui .wrapper{position:relative;left:0;z-index:99;height:100%;-webkit-transition:-webkit-transform .5s;transition:transform .5s}.yasgui .menu-open .menu-slide{left:600px;visibility:visible;-webkit-transition:all .5s;-moz-transition:all .5s;-ms-transition:all .5s;-o-transition:all .5s;transition:all .5s;-webkit-transform:translate3d(-100%,0,0) rotateY(0deg);transform:translate3d(-100%,0,0) rotateY(0deg)}.yasgui .controlbar{position:relative;left:0;-webkit-transition:all .5s;-moz-transition:all .5s;-ms-transition:all .5s;-o-transition:all .5s;transition:all .5s;padding:5px 5px 0;border-left:1px solid #ddd}.yasgui .controlbar .endpointText{width:400px}.yasgui .controlbar .endpointText .endpointOptionRow{vertical-align:middle}.yasgui .controlbar .endpointText .endpointOptionRow:hover{background-color:#e6e6e6}.yasgui .controlbar .endpointText .endpointOptionRow .close{display:table-cell;vertical-align:middle}.yasgui .controlbar .endpointText .endpointOptionRow .endpointUrl{font-weight:700;font-size:.9;width:95%;-ms-word-break:break-all;word-break:break-all;word-break:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;-ms-hyphens:auto;hyphens:auto}.yasgui .controlbar .endpointText .endpointOptionRow .endpointTitle{font-size:12px;opacity:.5}.yasgui .controlbar>*{vertical-align:top;margin-right:5px;display:inline-block}.yasgui .controlbar .menuButton{display:inline-block;vertical-align:middle;padding-left:10px;padding-right:10px;height:34px}.yasgui .controlbar .menuButton:focus{outline:0;background-color:transparent;border-color:#ccc}.yasgui .controlbar .menuButton .icon-bar{margin-bottom:3px;display:block;width:20px;height:3px;background-color:#777;border-radius:1px}.yasgui .menu-open .controlbar{border-left:0;left:600px}.yasgui .selectize-control.plugin-remove_button .disabled [data-value] .remove{border-left-color:#fff}.yasgui .selectize-control.multi .selectize-input.disabled>div,.yasgui .selectize-control.multi .selectize-input.disabled>div.active{border:0 solid #fff}.yasgui .selectize-control.plugin-drag_drop.multi>.selectize-input>div.ui-sortable-placeholder{visibility:visible!important;background:#f2f2f2!important;background:rgba(0,0,0,.06)!important;border:0!important;-webkit-box-shadow:inset 0 0 12px 4px #fff;box-shadow:inset 0 0 12px 4px #fff}.yasgui .selectize-control.plugin-drag_drop .ui-sortable-placeholder::after{content:'!';visibility:hidden}.yasgui .selectize-control.plugin-drag_drop .ui-sortable-helper{-webkit-box-shadow:0 2px 5px rgba(0,0,0,.2);box-shadow:0 2px 5px rgba(0,0,0,.2)}.yasgui .selectize-dropdown-header{position:relative;border-bottom:1px solid #d0d0d0;background:#f8f8f8;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.yasgui .selectize-dropdown-header-close{position:absolute;right:12px;top:50%;color:#333;opacity:.4;margin-top:-12px;line-height:20px;font-size:20px!important}.yasgui .selectize-dropdown-header-close:hover{color:#000}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup{border-right:1px solid #f2f2f2;border-top:0 none;float:left;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup:last-child{border-right:0 none}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup:before{display:none}.yasgui .selectize-dropdown.plugin-optgroup_columns .optgroup-header{border-top:0 none}.yasgui .selectize-control.plugin-remove_button [data-value]{position:relative;padding-right:24px!important}.yasgui .selectize-control.plugin-remove_button [data-value] .remove{z-index:1;position:absolute;top:0;right:0;bottom:0;width:17px;text-align:center;font-weight:700;font-size:12px;color:inherit;text-decoration:none;vertical-align:middle;display:inline-block;padding:1px 0 0;border-left:1px solid transparent;-webkit-border-radius:0 2px 2px 0;-moz-border-radius:0 2px 2px 0;border-radius:0 2px 2px 0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui .selectize-control.plugin-remove_button [data-value] .remove:hover{background:rgba(0,0,0,.05)}.yasgui .selectize-control.plugin-remove_button [data-value].active .remove{border-left-color:transparent}.yasgui .selectize-control.plugin-remove_button .disabled [data-value] .remove:hover{background:0 0}.yasgui .selectize-control.plugin-remove_button .disabled [data-value] .remove{border-left-color:rgba(77,77,77,0)}.yasgui .selectize-control{position:relative}.yasgui .selectize-dropdown,.yasgui .selectize-input,.yasgui .selectize-input input{color:#333;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;-webkit-font-smoothing:inherit}.yasgui .selectize-control.single .selectize-input.input-active,.yasgui .selectize-input{background:#fff;display:inline-block}.yasgui .selectize-input{border:1px solid #ccc;padding:6px 12px;display:inline-block;width:100%;overflow:hidden;position:relative;z-index:1;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-box-shadow:none;box-shadow:none;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.yasgui .selectize-control.multi .selectize-input.has-items{padding:5px 12px 2px}.yasgui .selectize-input.full{background-color:#fff}.yasgui .selectize-input.disabled,.yasgui .selectize-input.disabled *{cursor:default!important}.yasgui .selectize-input>*{vertical-align:baseline;display:-moz-inline-stack;display:inline-block;zoom:1}.yasgui .selectize-control.multi .selectize-input>div{cursor:pointer;margin:0 3px 3px 0;padding:1px 3px;background:#efefef;color:#333;border:0 solid transparent}.yasgui .selectize-control.multi .selectize-input>div.active{background:#428bca;color:#fff;border:0 solid transparent}.yasgui .selectize-control.multi .selectize-input.disabled>div,.yasgui .selectize-control.multi .selectize-input.disabled>div.active{color:grey;background:#fff;border:0 solid rgba(77,77,77,0)}.yasgui .selectize-input>input{display:inline-block!important;padding:0!important;min-height:0!important;max-height:none!important;max-width:100%!important;margin:0!important;text-indent:0!important;border:0!important;background:0 0!important;line-height:inherit!important;-webkit-user-select:auto!important;-webkit-box-shadow:none!important;box-shadow:none!important}.yasgui .selectize-input>input::-ms-clear{display:none}.yasgui .selectize-input>input:focus{outline:0!important}.yasgui .selectize-input::after{content:' ';display:block;clear:left}.yasgui .selectize-input.dropdown-active::before{content:' ';position:absolute;background:#fff;height:1px;bottom:0;left:0;right:0}.yasgui .selectize-dropdown{position:absolute;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.yasgui .selectize-dropdown [data-selectable]{cursor:pointer;overflow:hidden}.yasgui .selectize-dropdown [data-selectable] .highlight{background:rgba(255,237,40,.4);-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px}.yasgui .selectize-dropdown .optgroup-header,.yasgui .selectize-dropdown [data-selectable]{padding:3px 12px}.yasgui .selectize-dropdown .optgroup:first-child .optgroup-header{border-top:0 none}.yasgui .selectize-dropdown .optgroup-header{color:#777;background:#fff;cursor:default}.yasgui .selectize-dropdown .active{background-color:#f5f5f5;color:#262626}.yasgui .selectize-dropdown .active.create{color:#262626}.yasgui .selectize-dropdown .create{color:rgba(51,51,51,.5)}.yasgui .selectize-dropdown-content{overflow-y:auto;overflow-x:hidden;max-height:200px}.yasgui .selectize-control.single .selectize-input,.yasgui .selectize-control.single .selectize-input input{cursor:pointer}.yasgui .selectize-control.single .selectize-input.input-active,.yasgui .selectize-control.single .selectize-input.input-active input{cursor:text}.yasgui .selectize-control.single .selectize-input:after{content:' ';display:block;position:absolute;top:50%;right:17px;margin-top:-3px;width:0;height:0;border-style:solid;border-width:5px 5px 0;border-color:#333 transparent transparent}.yasgui .selectize-control.single .selectize-input.dropdown-active:after{margin-top:-4px;border-width:0 5px 5px;border-color:transparent transparent #333}.yasgui .selectize-control.rtl.single .selectize-input:after{left:17px;right:auto}.yasgui .selectize-control.rtl .selectize-input>input{margin:0 4px 0 -2px!important}.yasgui .selectize-control .selectize-input.disabled{opacity:.5;background-color:#fff}.yasgui .selectize-dropdown,.yasgui .selectize-dropdown.form-control{height:auto;padding:0;margin:2px 0 0;z-index:1000;background:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.yasgui .selectize-dropdown .optgroup-header{font-size:12px;line-height:1.42857}.yasgui .selectize-dropdown .optgroup:first-child:before{display:none}.yasgui .selectize-dropdown .optgroup:before{content:' ';display:block;height:1px;margin:9px -12px;overflow:hidden;background-color:#e5e5e5}.yasgui .selectize-dropdown-content{padding:5px 0}.yasgui .selectize-dropdown-header{padding:6px 12px}.yasgui .selectize-input{min-height:34px}.yasgui .selectize-input.dropdown-active{-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.yasgui .selectize-input.dropdown-active::before{display:none}.yasgui .selectize-input.focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.yasgui .has-error .selectize-input{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.yasgui .has-error .selectize-input:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.yasgui .selectize-control.multi .selectize-input.has-items{padding-left:9px;padding-right:9px}.yasgui .selectize-control.multi .selectize-input>div{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.yasgui .form-control.selectize-control{padding:0;height:auto;border:none;background:0 0;-webkit-box-shadow:none;box-shadow:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.yasqe{@-moz-keyframes blink { 0% { background:#7e7}@-webkit-keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}@keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}.yasqe .CodeMirror{font-family:monospace;height:300px}.yasqe .CodeMirror-scroll{overflow:auto}.yasqe .CodeMirror-lines{padding:4px 0}.yasqe .CodeMirror pre{padding:0 4px}.yasqe .CodeMirror-gutter-filler,.yasqe .CodeMirror-scrollbar-filler{background-color:#fff}.yasqe .CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.yasqe .CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;-moz-box-sizing:content-box;box-sizing:content-box}.yasqe .CodeMirror-guttermarker{color:#000}.yasqe .CodeMirror-guttermarker-subtle{color:#999}.yasqe .CodeMirror div.CodeMirror-cursor{border-left:1px solid #000}.yasqe .CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.yasqe .CodeMirror.cm-fat-cursor div.CodeMirror-cursor{width:auto;border:0;background:#7e7}.yasqe .CodeMirror.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.yasqe .cm-animate-fat-cursor{width:auto;border:0;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.yasqe .cm-tab{display:inline-block;text-decoration:inherit}.yasqe .CodeMirror-ruler{border-left:1px solid #ccc;position:absolute}.yasqe .cm-s-default .cm-keyword{color:#708}.yasqe .cm-s-default .cm-atom{color:#219}.yasqe .cm-s-default .cm-number{color:#164}.yasqe .cm-s-default .cm-def{color:#00f}.yasqe .cm-s-default .cm-variable-2{color:#05a}.yasqe .cm-s-default .cm-variable-3{color:#085}.yasqe .cm-s-default .cm-comment{color:#a50}.yasqe .cm-s-default .cm-string{color:#a11}.yasqe .cm-s-default .cm-string-2{color:#f50}.yasqe .cm-s-default .cm-meta,.yasqe .cm-s-default .cm-qualifier{color:#555}.yasqe .cm-s-default .cm-builtin{color:#30a}.yasqe .cm-s-default .cm-bracket{color:#997}.yasqe .cm-s-default .cm-tag{color:#170}.yasqe .cm-s-default .cm-attribute{color:#00c}.yasqe .cm-s-default .cm-header{color:#00f}.yasqe .cm-s-default .cm-quote{color:#090}.yasqe .cm-s-default .cm-hr{color:#999}.yasqe .cm-s-default .cm-link{color:#00c}.yasqe .cm-negative{color:#d44}.yasqe .cm-positive{color:#292}.yasqe .cm-header,.yasqe .cm-strong{font-weight:700}.yasqe .cm-em{font-style:italic}.yasqe .cm-link{text-decoration:underline}.yasqe .cm-strikethrough{text-decoration:line-through}.yasqe .cm-invalidchar,.yasqe .cm-s-default .cm-error{color:red}.yasqe div.CodeMirror span.CodeMirror-matchingbracket{color:#0f0}.yasqe div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#f22}.yasqe .CodeMirror-matchingtag{background:rgba(255,150,0,.3)}.yasqe .CodeMirror-activeline-background{background:#e8f2ff}.yasqe .CodeMirror{position:relative;overflow:hidden;background:#fff;color:#000}.yasqe .CodeMirror-scroll{margin-bottom:-30px;margin-right:-30px;padding-bottom:30px;height:100%;outline:0;position:relative;-moz-box-sizing:content-box;box-sizing:content-box}.yasqe .CodeMirror-sizer{position:relative;border-right:30px solid transparent;-moz-box-sizing:content-box;box-sizing:content-box}.yasqe .CodeMirror-gutter-filler,.yasqe .CodeMirror-hscrollbar,.yasqe .CodeMirror-scrollbar-filler,.yasqe .CodeMirror-vscrollbar{position:absolute;z-index:6;display:none}.yasqe .CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.yasqe .CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.yasqe .CodeMirror-scrollbar-filler{right:0;bottom:0}.yasqe .CodeMirror-gutter-filler{left:0;bottom:0}.yasqe .CodeMirror-gutters{position:absolute;left:0;top:0;padding-bottom:30px;z-index:3}.yasqe .CodeMirror-gutter{white-space:normal;height:100%;-moz-box-sizing:content-box;box-sizing:content-box;padding-bottom:30px;margin-bottom:-32px;display:inline-block}.yasqe .CodeMirror-gutter-wrapper{position:absolute;z-index:4;height:100%}.yasqe .CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.yasqe .CodeMirror-lines{cursor:text;min-height:1px}.yasqe .CodeMirror pre{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:0 0;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible}.yasqe .CodeMirror-wrap pre{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.yasqe .CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.yasqe .CodeMirror-linewidget{position:relative;z-index:2;overflow:auto}.yasqe .CodeMirror-wrap .CodeMirror-scroll{overflow-x:hidden}.yasqe .CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.yasqe .CodeMirror-measure pre{position:static}.yasqe .CodeMirror div.CodeMirror-cursor{position:absolute;border-right:none;width:0}.yasqe div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}.yasqe .CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.yasqe .CodeMirror-selected{background:#d9d9d9}.yasqe .CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.yasqe .CodeMirror-crosshair{cursor:crosshair}.yasqe .cm-searching{background:#ffa;background:rgba(255,255,0,.4)}.yasqe .cm-force-border{padding-right:.1px}@media print{.yasqe .CodeMirror div.CodeMirror-cursors{visibility:hidden}}.yasqe .cm-tab-wrap-hack:after{content:''}.yasqe span.CodeMirror-selectedtext{background:0 0}.yasqe .CodeMirror-fullscreen{position:fixed;top:0;left:0;right:0;bottom:0;height:auto;z-index:9}.yasqe .CodeMirror-foldmarker{color:#00f;text-shadow:#b9f 1px 1px 2px,#b9f -1px -1px 2px,#b9f 1px -1px 2px,#b9f -1px 1px 2px;font-family:arial;line-height:.3;cursor:pointer}.yasqe .CodeMirror-foldgutter{width:.7em}.yasqe .CodeMirror-foldgutter-folded,.yasqe .CodeMirror-foldgutter-open{cursor:pointer}.yasqe .CodeMirror-foldgutter-open:after{content:"\25BE"}.yasqe .CodeMirror-foldgutter-folded:after{content:"\25B8"}.yasqe .svgImg{display:inline-block}.yasqe .CodeMirror{line-height:1.5em;border:1px solid #d1d1d1}.yasqe pre{font-size:13px}.yasqe span.cm-error{border-bottom:2px dotted red}.yasqe .gutterErrorBar{width:4px}.yasqe .yasqe_buttons{position:absolute;top:5px;right:5px;z-index:5}.yasqe .yasqe_buttons div{vertical-align:top;margin-left:5px}.yasqe .yasqe_queryButton{display:inline-block;cursor:pointer;width:40px;height:40px}.yasqe .yasqe_queryButton .svgImg{display:block}.yasqe .yasqe_share{cursor:pointer;height:20px;width:20px;margin-top:3px}.yasqe .yasqe_sharePopup{position:absolute;padding:6px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05);width:400px;height:auto}.yasqe .yasqe_sharePopup textarea{width:100%}.yasqe .completionNotification{color:#999;background-color:#f7f7f7;position:absolute;padding:0 5px;right:0;bottom:0;font-size:90%}.yasqe .CodeMirror-fullscreen .fullscreenToggleBtns .yasqe_smallscreenBtn{display:inline-block}.yasqe .CodeMirror-fullscreen .fullscreenToggleBtns .yasqe_fullscreenBtn{display:none}.yasqe .fullscreenToggleBtns{display:inline-block;margin-top:3px}.yasqe .fullscreenToggleBtns div{cursor:pointer;width:20px;height:20px}.yasqe .fullscreenToggleBtns .yasqe_smallscreenBtn{display:none}.yasqe .parseErrorIcon{width:15px;height:15px}.yasqe .yasqe_tooltip{display:inline;background:#333;background:rgba(0,0,0,.8);border-radius:5px;bottom:26px;color:#fff;left:20%;padding:5px 15px;position:absolute;width:220px;white-space:-moz-pre-wrap!important;white-space:-pre-wrap;white-space:-o-pre-wrap;white-space:pre-wrap;white-space:normal}.yasqe .notificationLoader{width:18px;height:18px;vertical-align:middle}.CodeMirror-hints{position:absolute;z-index:10;overflow:hidden;list-style:none;margin:0;padding:2px;-webkit-box-shadow:2px 3px 5px rgba(0,0,0,.2);-moz-box-shadow:2px 3px 5px rgba(0,0,0,.2);box-shadow:2px 3px 5px rgba(0,0,0,.2);border-radius:3px;border:1px solid silver;background:#fff;font-size:90%;font-family:monospace;max-height:20em;overflow-y:auto}.CodeMirror-hint{margin:0;padding:0 4px;border-radius:2px;overflow:hidden;white-space:pre;color:#000;cursor:pointer}li.CodeMirror-hint-active{background:#08f;color:#fff}.CodeMirror-hint{max-width:30em}.yasr{padding-top:5px;background-color:#fff;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857;color:#333;@-moz-keyframes blink { 0% { background:#7e7}50%{background:0 0}100%{background:#7e7}@-webkit-keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}@keyframes blink{0%{background:#7e7}50%{background:0 0}100%{background:#7e7}}.yasr .svgImg{display:inline-block;bottom:-2px}.yasr button.btn_smallscreen{display:none}.yasr button.btn_fullscreen div,.yasr button.btn_smallscreen div{width:15px;height:15px}.yasr.yasr_fullscreen{z-index:10;position:fixed;top:0;bottom:0;left:0;right:0}.yasr.yasr_fullscreen .btn_smallscreen{display:inline-block}.yasr.yasr_fullscreen .btn_fullscreen{display:none}.yasr table.dataTable{width:100%;margin:0 auto;clear:both;border-collapse:separate;border-spacing:0}.yasr table.dataTable tfoot th,.yasr table.dataTable thead th{font-weight:700}.yasr table.dataTable thead td,.yasr table.dataTable thead th{padding:10px 18px;border-bottom:1px solid #111}.yasr table.dataTable thead td:active,.yasr table.dataTable thead th:active{outline:0}.yasr table.dataTable tfoot td,.yasr table.dataTable tfoot th{padding:10px 18px 6px;border-top:1px solid #111}.yasr table.dataTable thead .sorting,.yasr table.dataTable thead .sorting_asc,.yasr table.dataTable thead .sorting_desc{cursor:pointer}.yasr table.dataTable thead .sorting{background:url(../images/sort_both.png) center right no-repeat}.yasr table.dataTable thead .sorting_asc{background:url(../images/sort_asc.png) center right no-repeat}.yasr table.dataTable thead .sorting_desc{background:url(../images/sort_desc.png) center right no-repeat}.yasr table.dataTable thead .sorting_asc_disabled{background:url(../images/sort_asc_disabled.png) center right no-repeat}.yasr table.dataTable thead .sorting_desc_disabled{background:url(../images/sort_desc_disabled.png) center right no-repeat}.yasr table.dataTable tbody tr{background-color:#fff}.yasr table.dataTable tbody tr.selected{background-color:#b0bed9}.yasr table.dataTable tbody td,.yasr table.dataTable tbody th{padding:8px 10px}.yasr table.dataTable.display tbody td,.yasr table.dataTable.display tbody th,.yasr table.dataTable.row-border tbody td,.yasr table.dataTable.row-border tbody th{border-top:1px solid #ddd}.yasr table.dataTable.display tbody tr:first-child td,.yasr table.dataTable.display tbody tr:first-child th,.yasr table.dataTable.row-border tbody tr:first-child td,.yasr table.dataTable.row-border tbody tr:first-child th{border-top:none}.yasr table.dataTable.cell-border tbody td,.yasr table.dataTable.cell-border tbody th{border-top:1px solid #ddd;border-right:1px solid #ddd}.yasr table.dataTable.cell-border tbody tr td:first-child,.yasr table.dataTable.cell-border tbody tr th:first-child{border-left:1px solid #ddd}.yasr table.dataTable.cell-border tbody tr:first-child td,.yasr table.dataTable.cell-border tbody tr:first-child th{border-top:none}.yasr table.dataTable.display tbody tr.odd,.yasr table.dataTable.stripe tbody tr.odd{background-color:#f9f9f9}.yasr table.dataTable.display tbody tr.odd.selected,.yasr table.dataTable.stripe tbody tr.odd.selected{background-color:#abb9d3}.yasr table.dataTable.display tbody tr.even:hover,.yasr table.dataTable.display tbody tr.odd:hover,.yasr table.dataTable.display tbody tr:hover,.yasr table.dataTable.hover tbody tr.even:hover,.yasr table.dataTable.hover tbody tr.odd:hover,.yasr table.dataTable.hover tbody tr:hover{background-color:#f5f5f5}.yasr table.dataTable.display tbody tr.even:hover.selected,.yasr table.dataTable.display tbody tr.odd:hover.selected,.yasr table.dataTable.display tbody tr:hover.selected,.yasr table.dataTable.hover tbody tr.even:hover.selected,.yasr table.dataTable.hover tbody tr.odd:hover.selected,.yasr table.dataTable.hover tbody tr:hover.selected{background-color:#a9b7d1}.yasr table.dataTable.display tbody tr>.sorting_1,.yasr table.dataTable.display tbody tr>.sorting_2,.yasr table.dataTable.display tbody tr>.sorting_3,.yasr table.dataTable.order-column tbody tr>.sorting_1,.yasr table.dataTable.order-column tbody tr>.sorting_2,.yasr table.dataTable.order-column tbody tr>.sorting_3{background-color:#f9f9f9}.yasr table.dataTable.display tbody tr.selected>.sorting_1,.yasr table.dataTable.display tbody tr.selected>.sorting_2,.yasr table.dataTable.display tbody tr.selected>.sorting_3,.yasr table.dataTable.order-column tbody tr.selected>.sorting_1,.yasr table.dataTable.order-column tbody tr.selected>.sorting_2,.yasr table.dataTable.order-column tbody tr.selected>.sorting_3{background-color:#acbad4}.yasr table.dataTable.display tbody tr.odd>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.odd>.sorting_1{background-color:#f1f1f1}.yasr table.dataTable.display tbody tr.odd>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.odd>.sorting_2{background-color:#f3f3f3}.yasr table.dataTable.display tbody tr.odd>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.odd>.sorting_3{background-color:#f5f5f5}.yasr table.dataTable.display tbody tr.odd.selected>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_1{background-color:#a6b3cd}.yasr table.dataTable.display tbody tr.odd.selected>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_2{background-color:#a7b5ce}.yasr table.dataTable.display tbody tr.odd.selected>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.odd.selected>.sorting_3{background-color:#a9b6d0}.yasr table.dataTable.display tbody tr.even>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.even>.sorting_1{background-color:#f9f9f9}.yasr table.dataTable.display tbody tr.even>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.even>.sorting_2{background-color:#fbfbfb}.yasr table.dataTable.display tbody tr.even>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.even>.sorting_3{background-color:#fdfdfd}.yasr table.dataTable.display tbody tr.even.selected>.sorting_1,.yasr table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_1{background-color:#acbad4}.yasr table.dataTable.display tbody tr.even.selected>.sorting_2,.yasr table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_2{background-color:#adbbd6}.yasr table.dataTable.display tbody tr.even.selected>.sorting_3,.yasr table.dataTable.order-column.stripe tbody tr.even.selected>.sorting_3{background-color:#afbdd8}.yasr table.dataTable.display tbody tr.even:hover>.sorting_1,.yasr table.dataTable.display tbody tr.odd:hover>.sorting_1,.yasr table.dataTable.display tbody tr:hover>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.even:hover>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.odd:hover>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr:hover>.sorting_1{background-color:#eaeaea}.yasr table.dataTable.display tbody tr.even:hover>.sorting_2,.yasr table.dataTable.display tbody tr.odd:hover>.sorting_2,.yasr table.dataTable.display tbody tr:hover>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.even:hover>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.odd:hover>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr:hover>.sorting_2{background-color:#ebebeb}.yasr table.dataTable.display tbody tr.even:hover>.sorting_3,.yasr table.dataTable.display tbody tr.odd:hover>.sorting_3,.yasr table.dataTable.display tbody tr:hover>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.even:hover>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.odd:hover>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr:hover>.sorting_3{background-color:#eee}.yasr table.dataTable.display tbody tr.even:hover.selected>.sorting_1,.yasr table.dataTable.display tbody tr.odd:hover.selected>.sorting_1,.yasr table.dataTable.display tbody tr:hover.selected>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.even:hover.selected>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr.odd:hover.selected>.sorting_1,.yasr table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_1{background-color:#a1aec7}.yasr table.dataTable.display tbody tr.even:hover.selected>.sorting_2,.yasr table.dataTable.display tbody tr.odd:hover.selected>.sorting_2,.yasr table.dataTable.display tbody tr:hover.selected>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.even:hover.selected>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr.odd:hover.selected>.sorting_2,.yasr table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_2{background-color:#a2afc8}.yasr table.dataTable.display tbody tr.even:hover.selected>.sorting_3,.yasr table.dataTable.display tbody tr.odd:hover.selected>.sorting_3,.yasr table.dataTable.display tbody tr:hover.selected>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.even:hover.selected>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr.odd:hover.selected>.sorting_3,.yasr table.dataTable.order-column.hover tbody tr:hover.selected>.sorting_3{background-color:#a4b2cb}.yasr table.dataTable.no-footer{border-bottom:1px solid #111}.yasr table.dataTable.nowrap td,.yasr table.dataTable.nowrap th{white-space:nowrap}.yasr table.dataTable.compact thead td,.yasr table.dataTable.compact thead th{padding:5px 9px}.yasr table.dataTable.compact tfoot td,.yasr table.dataTable.compact tfoot th{padding:5px 9px 3px}.yasr table.dataTable.compact tbody td,.yasr table.dataTable.compact tbody th{padding:4px 5px}.yasr table.dataTable td.dt-left,.yasr table.dataTable th.dt-left{text-align:left}.yasr table.dataTable td.dataTables_empty,.yasr table.dataTable td.dt-center,.yasr table.dataTable th.dt-center{text-align:center}.yasr table.dataTable td.dt-right,.yasr table.dataTable th.dt-right{text-align:right}.yasr table.dataTable td.dt-justify,.yasr table.dataTable th.dt-justify{text-align:justify}.yasr table.dataTable td.dt-nowrap,.yasr table.dataTable th.dt-nowrap{white-space:nowrap}.yasr table.dataTable tfoot td.dt-head-left,.yasr table.dataTable tfoot th.dt-head-left,.yasr table.dataTable thead td.dt-head-left,.yasr table.dataTable thead th.dt-head-left{text-align:left}.yasr table.dataTable tfoot td.dt-head-center,.yasr table.dataTable tfoot th.dt-head-center,.yasr table.dataTable thead td.dt-head-center,.yasr table.dataTable thead th.dt-head-center{text-align:center}.yasr table.dataTable tfoot td.dt-head-right,.yasr table.dataTable tfoot th.dt-head-right,.yasr table.dataTable thead td.dt-head-right,.yasr table.dataTable thead th.dt-head-right{text-align:right}.yasr table.dataTable tfoot td.dt-head-justify,.yasr table.dataTable tfoot th.dt-head-justify,.yasr table.dataTable thead td.dt-head-justify,.yasr table.dataTable thead th.dt-head-justify{text-align:justify}.yasr table.dataTable tfoot td.dt-head-nowrap,.yasr table.dataTable tfoot th.dt-head-nowrap,.yasr table.dataTable thead td.dt-head-nowrap,.yasr table.dataTable thead th.dt-head-nowrap{white-space:nowrap}.yasr table.dataTable tbody td.dt-body-left,.yasr table.dataTable tbody th.dt-body-left{text-align:left}.yasr table.dataTable tbody td.dt-body-center,.yasr table.dataTable tbody th.dt-body-center{text-align:center}.yasr table.dataTable tbody td.dt-body-right,.yasr table.dataTable tbody th.dt-body-right{text-align:right}.yasr table.dataTable tbody td.dt-body-justify,.yasr table.dataTable tbody th.dt-body-justify{text-align:justify}.yasr table.dataTable tbody td.dt-body-nowrap,.yasr table.dataTable tbody th.dt-body-nowrap{white-space:nowrap}.yasr table.dataTable,.yasr table.dataTable td,.yasr table.dataTable th{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .dataTables_wrapper{position:relative;clear:both;zoom:1}.yasr .dataTables_wrapper .dataTables_filter{float:right;text-align:right}.yasr .dataTables_wrapper .dataTables_filter input{margin-left:.5em}.yasr .dataTables_wrapper .dataTables_info{clear:both;float:left;padding-top:.755em}.yasr .dataTables_wrapper .dataTables_paginate{float:right;text-align:right;padding-top:.25em}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button{box-sizing:border-box;display:inline-block;min-width:1.5em;padding:.5em 1em;margin-left:2px;text-align:center;text-decoration:none!important;cursor:pointer;color:#333!important;border:1px solid transparent}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.current,.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover{color:#333!important;border:1px solid #cacaca;background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#fff),color-stop(100%,#dcdcdc));background:-webkit-linear-gradient(top,#fff 0,#dcdcdc 100%);background:-moz-linear-gradient(top,#fff 0,#dcdcdc 100%);background:-ms-linear-gradient(top,#fff 0,#dcdcdc 100%);background:-o-linear-gradient(top,#fff 0,#dcdcdc 100%);background:linear-gradient(to bottom,#fff 0,#dcdcdc 100%)}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.disabled,.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:active,.yasr .dataTables_wrapper .dataTables_paginate .paginate_button.disabled:hover{cursor:default;color:#666!important;border:1px solid transparent;background:0 0;box-shadow:none}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button:hover{color:#fff!important;border:1px solid #111;background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#585858),color-stop(100%,#111));background:-webkit-linear-gradient(top,#585858 0,#111 100%);background:-moz-linear-gradient(top,#585858 0,#111 100%);background:-ms-linear-gradient(top,#585858 0,#111 100%);background:-o-linear-gradient(top,#585858 0,#111 100%);background:linear-gradient(to bottom,#585858 0,#111 100%)}.yasr .dataTables_wrapper .dataTables_paginate .paginate_button:active{outline:0;background:-webkit-gradient(linear,left top,left bottom,color-stop(0,#2b2b2b),color-stop(100%,#0c0c0c));background:-webkit-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:-moz-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:-ms-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:-o-linear-gradient(top,#2b2b2b 0,#0c0c0c 100%);background:linear-gradient(to bottom,#2b2b2b 0,#0c0c0c 100%);box-shadow:inset 0 0 3px #111}.yasr .dataTables_wrapper .dataTables_processing{position:absolute;top:50%;left:50%;width:100%;height:40px;margin-left:-50%;margin-top:-25px;padding-top:20px;text-align:center;font-size:1.2em;background:-webkit-gradient(linear,left top,right top,color-stop(0,rgba(255,255,255,0)),color-stop(25%,rgba(255,255,255,.9)),color-stop(75%,rgba(255,255,255,.9)),color-stop(100%,rgba(255,255,255,0)));background:-webkit-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:-moz-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:-ms-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:-o-linear-gradient(left,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%);background:linear-gradient(to right,rgba(255,255,255,0) 0,rgba(255,255,255,.9) 25%,rgba(255,255,255,.9) 75%,rgba(255,255,255,0) 100%)}.yasr .dataTables_wrapper .dataTables_filter,.yasr .dataTables_wrapper .dataTables_info,.yasr .dataTables_wrapper .dataTables_length,.yasr .dataTables_wrapper .dataTables_paginate,.yasr .dataTables_wrapper .dataTables_processing{color:#333}.yasr .dataTables_wrapper .dataTables_scroll{clear:both}.yasr .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody{-webkit-overflow-scrolling:touch}.yasr .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody td>div.dataTables_sizing,.yasr .dataTables_wrapper .dataTables_scroll div.dataTables_scrollBody th>div.dataTables_sizing{height:0;overflow:hidden;margin:0!important;padding:0!important}.yasr .dataTables_wrapper.no-footer .dataTables_scrollBody{border-bottom:1px solid #111}.yasr .dataTables_wrapper.no-footer div.dataTables_scrollBody table,.yasr .dataTables_wrapper.no-footer div.dataTables_scrollHead table{border-bottom:none}.yasr .dataTables_wrapper:after{visibility:hidden;display:block;content:"";clear:both;height:0}@media screen and (max-width:767px){.yasr .dataTables_wrapper .dataTables_info,.yasr .dataTables_wrapper .dataTables_paginate{float:none;text-align:center}.yasr .dataTables_wrapper .dataTables_paginate{margin-top:.5em}}@media screen and (max-width:640px){.yasr .dataTables_wrapper .dataTables_filter,.yasr .dataTables_wrapper .dataTables_length{float:none;text-align:center}.yasr .dataTables_wrapper .dataTables_filter{margin-top:.5em}}.yasr table.pvtTable{font-family:arial;font-size:8pt;text-align:left;border-collapse:collapse}.yasr table.pvtTable tr th{background-color:#e6EEEE;border:1px solid #CDCDCD;font-size:8pt;padding:5px}.yasr table.pvtTable .pvtColLabel{text-align:center}.yasr table.pvtTable .pvtTotalLabel{text-align:right}.yasr table.pvtTable tr td{color:#3D3D3D;padding:5px;background-color:#FFF;border:1px solid #CDCDCD;vertical-align:top;text-align:right}.yasr .pvtGrandTotal,.yasr .pvtTotal{font-weight:700}.yasr .pvtVals{text-align:center}.yasr .pvtAggregator{margin-bottom:5px}.yasr .pvtAxisContainer,.yasr .pvtVals{border:1px solid gray;background:#EEE;padding:5px;min-width:20px;min-height:20px}.yasr .pvtAxisContainer li{padding:8px 6px;list-style-type:none;cursor:move}.yasr .pvtAxisContainer li.pvtPlaceholder{-webkit-border-radius:5px;padding:3px 15px;-moz-border-radius:5px;border-radius:5px;border:1px dashed #aaa}.yasr .pvtAxisContainer li span.pvtAttr{background:#F3F3F3;border:1px solid #DEDEDE;padding:2px 5px;white-space:nowrap;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.yasr .pvtTriangle{cursor:pointer;color:grey}.yasr .pvtHorizList li{display:inline}.yasr .pvtVertList{vertical-align:top}.yasr .pvtFilteredAttribute{font-style:italic}.yasr .pvtFilterBox{z-index:100;width:280px;border:1px solid gray;background-color:#fff;position:absolute;padding:20px;text-align:center}.yasr .pvtFilterBox h4{margin:0}.yasr .pvtCheckContainer{text-align:left;overflow:scroll;width:100%;max-height:200px}.yasr .pvtCheckContainer p{margin:5px}.yasr .CodeMirror{font-family:monospace;height:300px}.yasr .CodeMirror-lines{padding:4px 0}.yasr .CodeMirror pre{padding:0 4px}.yasr .CodeMirror-gutter-filler,.yasr .CodeMirror-scrollbar-filler{background-color:#fff}.yasr .CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.yasr .CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .CodeMirror-guttermarker{color:#000}.yasr .CodeMirror-guttermarker-subtle{color:#999}.yasr .CodeMirror div.CodeMirror-cursor{border-left:1px solid #000}.yasr .CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.yasr .CodeMirror.cm-fat-cursor div.CodeMirror-cursor{width:auto;border:0;background:#7e7}.yasr .CodeMirror.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.yasr .cm-animate-fat-cursor{width:auto;border:0;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.yasr .cm-tab{display:inline-block;text-decoration:inherit}.yasr .CodeMirror-ruler{border-left:1px solid #ccc;position:absolute}.yasr .cm-s-default .cm-keyword{color:#708}.yasr .cm-s-default .cm-atom{color:#219}.yasr .cm-s-default .cm-number{color:#164}.yasr .cm-s-default .cm-def{color:#00f}.yasr .cm-s-default .cm-variable-2{color:#05a}.yasr .cm-s-default .cm-variable-3{color:#085}.yasr .cm-s-default .cm-comment{color:#a50}.yasr .cm-s-default .cm-string{color:#a11}.yasr .cm-s-default .cm-string-2{color:#f50}.yasr .cm-s-default .cm-meta,.yasr .cm-s-default .cm-qualifier{color:#555}.yasr .cm-s-default .cm-builtin{color:#30a}.yasr .cm-s-default .cm-bracket{color:#997}.yasr .cm-s-default .cm-tag{color:#170}.yasr .cm-s-default .cm-attribute{color:#00c}.yasr .cm-s-default .cm-header{color:#00f}.yasr .cm-s-default .cm-quote{color:#090}.yasr .cm-s-default .cm-hr{color:#999}.yasr .cm-s-default .cm-link{color:#00c}.yasr .cm-negative{color:#d44}.yasr .cm-positive{color:#292}.yasr .cm-header,.yasr .cm-strong{font-weight:700}.yasr .cm-em{font-style:italic}.yasr .cm-link{text-decoration:underline}.yasr .cm-strikethrough{text-decoration:line-through}.yasr .cm-invalidchar,.yasr .cm-s-default .cm-error{color:red}.yasr div.CodeMirror span.CodeMirror-matchingbracket{color:#0f0}.yasr div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#f22}.yasr .CodeMirror-matchingtag{background:rgba(255,150,0,.3)}.yasr .CodeMirror-activeline-background{background:#e8f2ff}.yasr .CodeMirror{line-height:1;position:relative;overflow:hidden;background:#fff;color:#000}.yasr .CodeMirror-scroll{overflow:scroll!important;margin-bottom:-30px;margin-right:-30px;padding-bottom:30px;height:100%;outline:0;position:relative;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .CodeMirror-sizer{position:relative;border-right:30px solid transparent;-moz-box-sizing:content-box;box-sizing:content-box}.yasr .CodeMirror-gutter-filler,.yasr .CodeMirror-hscrollbar,.yasr .CodeMirror-scrollbar-filler,.yasr .CodeMirror-vscrollbar{position:absolute;z-index:6;display:none}.yasr .CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.yasr .CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.yasr .CodeMirror-scrollbar-filler{right:0;bottom:0}.yasr .CodeMirror-gutter-filler{left:0;bottom:0}.yasr .CodeMirror-gutters{position:absolute;left:0;top:0;z-index:3}.yasr .CodeMirror-gutter{white-space:normal;height:100%;-moz-box-sizing:content-box;box-sizing:content-box;display:inline-block;margin-bottom:-30px}.yasr .CodeMirror-gutter-wrapper{position:absolute;z-index:4;height:100%}.yasr .CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.yasr .CodeMirror-lines{cursor:text;min-height:1px}.yasr .CodeMirror pre{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:0 0;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible}.yasr .CodeMirror-wrap pre{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.yasr .CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.yasr .CodeMirror-linewidget{position:relative;z-index:2;overflow:auto}.yasr .CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.yasr .CodeMirror-measure pre{position:static}.yasr .CodeMirror div.CodeMirror-cursor{position:absolute;border-right:none;width:0}.yasr div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}.yasr .CodeMirror-focused div.CodeMirror-cursors{visibility:visible}.yasr .CodeMirror-selected{background:#d9d9d9}.yasr .CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.yasr .CodeMirror-crosshair{cursor:crosshair}.yasr .cm-searching{background:#ffa;background:rgba(255,255,0,.4)}.yasr .cm-force-border{padding-right:.1px}@media print{.yasr .CodeMirror div.CodeMirror-cursors{visibility:hidden}}.yasr .cm-tab-wrap-hack:after{content:''}.yasr span.CodeMirror-selectedtext{background:0 0}.yasr .CodeMirror-foldmarker{color:#00f;text-shadow:#b9f 1px 1px 2px,#b9f -1px -1px 2px,#b9f 1px -1px 2px,#b9f -1px 1px 2px;font-family:arial;line-height:.3;cursor:pointer}.yasr .CodeMirror-foldgutter{width:.7em}.yasr .CodeMirror-foldgutter-folded,.yasr .CodeMirror-foldgutter-open{cursor:pointer}.yasr .CodeMirror-foldgutter-open:after{content:"\25BE"}.yasr .CodeMirror-foldgutter-folded:after{content:"\25B8"}.yasr a{color:#428bca;text-decoration:none}.yasr a:active,.yasr a:hover{outline:0;color:#2a6496;text-decoration:underline}.yasr th{text-align:left}.yasr .yasr_header *{z-index:5;position:relative}.yasr .yasr_header>*{margin-left:6px}.yasr .yasr_btn{color:#333;border:1px solid transparent;background-color:#fff;border-color:#ccc;border-width:1px;display:inline-block;text-align:center;vertical-align:middle;cursor:pointer;white-space:nowrap;padding:6px 12px;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-appearance:button;overflow:visible;box-sizing:border-box}.yasr .yasr_btn.btn_icon{padding:4px 8px}.yasr .yasr_btn.disabled,.yasr .yasr_btn[disabled]{cursor:default;opacity:.5;filter:alpha(opacity=50);-webkit-box-shadow:none;box-shadow:none}.yasr .yasr_btn:hover{outline:0;background-color:#ebebeb;border-color:#adadad}.yasr .yasr_btn.selected,.yasr .yasr_btn:focus{color:#fff;outline:0;background-color:#337ab7;border-color:#337ab7}.yasr .yasr_btn.btn_icon:focus{color:#333;border:1px solid transparent;background-color:#fff;border-color:#ccc}.yasr .yasr_downloadIcon div{height:15px;width:15px}.yasr .yasr_btnGroup{display:inline-block;vertical-align:middle}.yasr .yasr_btnGroup>button:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0}.yasr .yasr_btnGroup>button:last-child:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.yasr .yasr_btnGroup>button:not(:first-child):not(:last-child){border-radius:0}.yasr .yasr_btnGroup button+button{margin-left:-1px}.yasr .booleanResult{width:70px;margin:0 auto;vertical-align:middle}.yasr .booleanResult svg{margin-bottom:-10px;margin-right:7px}.yasr .errorResult{padding:10px}.yasr .errorResult span.exception{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em;background-color:#d9534f}.yasr .errorResult pre{display:block;padding:10px;margin:10px 0;font-size:13px;line-height:1.42857;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}.yasr .yasr_results .CodeMirror{border:1px solid #d1d1d1;margin-top:5px;height:100%}.yasr .dataTables_wrapper .dataTables_length{float:right;margin-left:10px}.yasr .dataTables_wrapper .dataTables_length label,.yasr .dataTables_wrapper .dataTables_length select{vertical-align:middle}.yasr table.dataTable thead th{background:0 0!important;border-right:1px dotted gray;padding:7px 0}.yasr table.dataTable thead th:first-child,.yasr table.dataTable thead th:last-child{border-right:0}.yasr table.dataTable thead th span{margin-left:5px}.yasr table.dataTable td div{-ms-word-break:break-all;word-break:break-all;word-break:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;-ms-hyphens:auto;hyphens:auto;padding:0 5px}.yasr .sortIcons{float:right;width:8px;height:13px;margin-right:10px}.yasr .pivotTable{margin-top:5px}.yasr .pivotTable>table{background-color:#fff}.yasr .pivotTable td.pvtAxisContainer,.yasr .pivotTable td.pvtVals{border:1px solid #ddd;background-color:transparent}.yasr .pivotTable li span.pvtAttr{background-color:#337ab7;color:#fff;padding:4px 7px}.yasr .pivotTable li span.pvtAttr svg{fill:#fff}.yasr .pivotTable li span.pvtAttr div{margin-left:6px;vertical-align:middle}.yasr .pivotTable .pvtCols{vertical-align:top}.yasr .pivotTable table.pvtTable tr th{background-color:#f2f2f2}.yasr .pivotTable table.pvtTable tr th.pvtAxisLabel{background-color:#337ab7;color:#fff}.yasr .pivotTable .containerHeader{margin-left:8px;margin-bottom:8px;font-style:italic;font-size:110%;color:#999;text-align:left}.yasr .pivotTable .pvtAttr .svgImg{width:14px;height:14px}.yasr .pivotTable .node{border:1px solid #fff;font:10px sans-serif;line-height:12px;overflow:hidden;position:absolute;text-indent:2px}.yasr .openPivotGchart{float:right;position:relative;display:none;top:-38px;margin-bottom:-38px}.yasr .openGchartBtn{float:right;position:relative;top:-35px;margin-bottom:-35px}.yasr .gchartWrapper{width:100%;height:600px;margin-top:2px}.modal-dialog.google-visualization-charteditor-dialog{z-index:11;width:auto;margin:inherit}div.modal-dialog.google-visualization-charteditor-dialog{z-index:100} | lucasls/cdnjs | ajax/libs/yasgui/0.0.6/yasgui.min.css | CSS | mit | 181,217 |
CKEDITOR.plugins.setLang("docprops","lt",{bgColor:"Fono spalva",bgFixed:"Neslenkantis fonas",bgImage:"Fono paveikslėlio nuoroda (URL)",charset:"Simbolių kodavimo lentelė",charsetASCII:"ASCII",charsetCE:"Centrinės Europos",charsetCR:"Kirilica",charsetCT:"Tradicinės kinų (Big5)",charsetGR:"Graikų",charsetJP:"Japonų",charsetKR:"Korėjiečių",charsetOther:"Kita simbolių kodavimo lentelė",charsetTR:"Turkų",charsetUN:"Unikodas (UTF-8)",charsetWE:"Vakarų Europos",chooseColor:"Pasirinkite",design:"Išdėstymas",
docTitle:"Puslapio antraštė",docType:"Dokumento tipo antraštė",docTypeOther:"Kita dokumento tipo antraštė",label:"Dokumento savybės",margin:"Puslapio kraštinės",marginBottom:"Apačioje",marginLeft:"Kairėje",marginRight:"Dešinėje",marginTop:"Viršuje",meta:"Meta duomenys",metaAuthor:"Autorius",metaCopyright:"Autorinės teisės",metaDescription:"Dokumento apibūdinimas",metaKeywords:"Dokumento indeksavimo raktiniai žodžiai (atskirti kableliais)",other:"\x3ckitas\x3e",previewHtml:'\x3cp\x3eTai yra \x3cstrong\x3epavyzdinis tekstas\x3c/strong\x3e. Jūs naudojate \x3ca href\x3d"javascript:void(0)"\x3eCKEditor\x3c/a\x3e.\x3c/p\x3e',
title:"Dokumento savybės",txtColor:"Teksto spalva",xhtmlDec:"Įtraukti XHTML deklaracijas"}); | lokeswaraswamy522/neonet | node_modules/ckeditor/plugins/docprops/lang/lt.js | JavaScript | mit | 1,268 |
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; }
if (!__coverage__['build/widget-base-ie/widget-base-ie.js']) {
__coverage__['build/widget-base-ie/widget-base-ie.js'] = {"path":"build/widget-base-ie/widget-base-ie.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0},"b":{"1":[0,0],"2":[0,0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0]},"f":{"1":0,"2":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":26},"end":{"line":1,"column":45}}},"2":{"name":"(anonymous_2)","line":19,"loc":{"start":{"line":19,"column":31},"end":{"line":19,"column":48}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":49,"column":47}},"2":{"start":{"line":8,"column":0},"end":{"line":16,"column":67}},"3":{"start":{"line":19,"column":0},"end":{"line":46,"column":2}},"4":{"start":{"line":21,"column":4},"end":{"line":23,"column":39}},"5":{"start":{"line":25,"column":4},"end":{"line":27,"column":5}},"6":{"start":{"line":26,"column":8},"end":{"line":26,"column":118}},"7":{"start":{"line":29,"column":4},"end":{"line":45,"column":5}},"8":{"start":{"line":30,"column":8},"end":{"line":30,"column":48}},"9":{"start":{"line":32,"column":8},"end":{"line":44,"column":9}},"10":{"start":{"line":33,"column":12},"end":{"line":35,"column":13}},"11":{"start":{"line":34,"column":16},"end":{"line":34,"column":45}},"12":{"start":{"line":37,"column":12},"end":{"line":37,"column":57}},"13":{"start":{"line":39,"column":12},"end":{"line":41,"column":13}},"14":{"start":{"line":40,"column":16},"end":{"line":40,"column":48}},"15":{"start":{"line":43,"column":12},"end":{"line":43,"column":43}}},"branchMap":{"1":{"line":25,"type":"if","locations":[{"start":{"line":25,"column":4},"end":{"line":25,"column":4}},{"start":{"line":25,"column":4},"end":{"line":25,"column":4}}]},"2":{"line":26,"type":"binary-expr","locations":[{"start":{"line":26,"column":43},"end":{"line":26,"column":45}},{"start":{"line":26,"column":49},"end":{"line":26,"column":55}},{"start":{"line":26,"column":59},"end":{"line":26,"column":116}}]},"3":{"line":29,"type":"if","locations":[{"start":{"line":29,"column":4},"end":{"line":29,"column":4}},{"start":{"line":29,"column":4},"end":{"line":29,"column":4}}]},"4":{"line":32,"type":"if","locations":[{"start":{"line":32,"column":8},"end":{"line":32,"column":8}},{"start":{"line":32,"column":8},"end":{"line":32,"column":8}}]},"5":{"line":33,"type":"if","locations":[{"start":{"line":33,"column":12},"end":{"line":33,"column":12}},{"start":{"line":33,"column":12},"end":{"line":33,"column":12}}]},"6":{"line":39,"type":"if","locations":[{"start":{"line":39,"column":12},"end":{"line":39,"column":12}},{"start":{"line":39,"column":12},"end":{"line":39,"column":12}}]}},"code":["(function () { YUI.add('widget-base-ie', function (Y, NAME) {","","/**"," * IE specific support for the widget-base module."," *"," * @module widget-base-ie"," */","var BOUNDING_BOX = \"boundingBox\","," CONTENT_BOX = \"contentBox\","," HEIGHT = \"height\","," OFFSET_HEIGHT = \"offsetHeight\","," EMPTY_STR = \"\","," IE = Y.UA.ie,"," heightReallyMinHeight = IE < 7,"," bbTempExpanding = Y.Widget.getClassName(\"tmp\", \"forcesize\"),"," contentExpanded = Y.Widget.getClassName(\"content\", \"expanded\");","","// TODO: Ideally we want to re-use the base _uiSizeCB impl","Y.Widget.prototype._uiSizeCB = function(expand) {",""," var bb = this.get(BOUNDING_BOX),"," cb = this.get(CONTENT_BOX),"," borderBoxSupported = this._bbs;",""," if (borderBoxSupported === undefined) {"," this._bbs = borderBoxSupported = !(IE && IE < 8 && bb.get(\"ownerDocument\").get(\"compatMode\") != \"BackCompat\");"," }",""," if (borderBoxSupported) {"," cb.toggleClass(contentExpanded, expand);"," } else {"," if (expand) {"," if (heightReallyMinHeight) {"," bb.addClass(bbTempExpanding);"," }",""," cb.set(OFFSET_HEIGHT, bb.get(OFFSET_HEIGHT));",""," if (heightReallyMinHeight) {"," bb.removeClass(bbTempExpanding);"," }"," } else {"," cb.setStyle(HEIGHT, EMPTY_STR);"," }"," }","};","","","}, '@VERSION@', {\"requires\": [\"widget-base\"]});","","}());"]};
}
var __cov__5xkELqleeuONdVWK9MW$A = __coverage__['build/widget-base-ie/widget-base-ie.js'];
__cov__5xkELqleeuONdVWK9MW$A.s['1']++;YUI.add('widget-base-ie',function(Y,NAME){__cov__5xkELqleeuONdVWK9MW$A.f['1']++;__cov__5xkELqleeuONdVWK9MW$A.s['2']++;var BOUNDING_BOX='boundingBox',CONTENT_BOX='contentBox',HEIGHT='height',OFFSET_HEIGHT='offsetHeight',EMPTY_STR='',IE=Y.UA.ie,heightReallyMinHeight=IE<7,bbTempExpanding=Y.Widget.getClassName('tmp','forcesize'),contentExpanded=Y.Widget.getClassName('content','expanded');__cov__5xkELqleeuONdVWK9MW$A.s['3']++;Y.Widget.prototype._uiSizeCB=function(expand){__cov__5xkELqleeuONdVWK9MW$A.f['2']++;__cov__5xkELqleeuONdVWK9MW$A.s['4']++;var bb=this.get(BOUNDING_BOX),cb=this.get(CONTENT_BOX),borderBoxSupported=this._bbs;__cov__5xkELqleeuONdVWK9MW$A.s['5']++;if(borderBoxSupported===undefined){__cov__5xkELqleeuONdVWK9MW$A.b['1'][0]++;__cov__5xkELqleeuONdVWK9MW$A.s['6']++;this._bbs=borderBoxSupported=!((__cov__5xkELqleeuONdVWK9MW$A.b['2'][0]++,IE)&&(__cov__5xkELqleeuONdVWK9MW$A.b['2'][1]++,IE<8)&&(__cov__5xkELqleeuONdVWK9MW$A.b['2'][2]++,bb.get('ownerDocument').get('compatMode')!='BackCompat'));}else{__cov__5xkELqleeuONdVWK9MW$A.b['1'][1]++;}__cov__5xkELqleeuONdVWK9MW$A.s['7']++;if(borderBoxSupported){__cov__5xkELqleeuONdVWK9MW$A.b['3'][0]++;__cov__5xkELqleeuONdVWK9MW$A.s['8']++;cb.toggleClass(contentExpanded,expand);}else{__cov__5xkELqleeuONdVWK9MW$A.b['3'][1]++;__cov__5xkELqleeuONdVWK9MW$A.s['9']++;if(expand){__cov__5xkELqleeuONdVWK9MW$A.b['4'][0]++;__cov__5xkELqleeuONdVWK9MW$A.s['10']++;if(heightReallyMinHeight){__cov__5xkELqleeuONdVWK9MW$A.b['5'][0]++;__cov__5xkELqleeuONdVWK9MW$A.s['11']++;bb.addClass(bbTempExpanding);}else{__cov__5xkELqleeuONdVWK9MW$A.b['5'][1]++;}__cov__5xkELqleeuONdVWK9MW$A.s['12']++;cb.set(OFFSET_HEIGHT,bb.get(OFFSET_HEIGHT));__cov__5xkELqleeuONdVWK9MW$A.s['13']++;if(heightReallyMinHeight){__cov__5xkELqleeuONdVWK9MW$A.b['6'][0]++;__cov__5xkELqleeuONdVWK9MW$A.s['14']++;bb.removeClass(bbTempExpanding);}else{__cov__5xkELqleeuONdVWK9MW$A.b['6'][1]++;}}else{__cov__5xkELqleeuONdVWK9MW$A.b['4'][1]++;__cov__5xkELqleeuONdVWK9MW$A.s['15']++;cb.setStyle(HEIGHT,EMPTY_STR);}}};},'@VERSION@',{'requires':['widget-base']});
| pombredanne/cdnjs | ajax/libs/yui/3.10.3/widget-base-ie/widget-base-ie-coverage.js | JavaScript | mit | 6,509 |
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; }
if (!__coverage__['build/event-mousewheel/event-mousewheel.js']) {
__coverage__['build/event-mousewheel/event-mousewheel.js'] = {"path":"build/event-mousewheel/event-mousewheel.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0},"b":{"1":[0,0],"2":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":28},"end":{"line":1,"column":47}}},"2":{"name":"(anonymous_2)","line":9,"loc":{"start":{"line":9,"column":14},"end":{"line":9,"column":29}}},"3":{"name":"(anonymous_3)","line":40,"loc":{"start":{"line":40,"column":8},"end":{"line":40,"column":19}}},"4":{"name":"(anonymous_4)","line":44,"loc":{"start":{"line":44,"column":12},"end":{"line":44,"column":23}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":50,"column":45}},"2":{"start":{"line":8,"column":0},"end":{"line":25,"column":6}},"3":{"start":{"line":10,"column":8},"end":{"line":10,"column":47}},"4":{"start":{"line":11,"column":8},"end":{"line":16,"column":9}},"5":{"start":{"line":12,"column":12},"end":{"line":12,"column":36}},"6":{"start":{"line":13,"column":12},"end":{"line":13,"column":34}},"7":{"start":{"line":15,"column":12},"end":{"line":15,"column":34}},"8":{"start":{"line":18,"column":8},"end":{"line":22,"column":9}},"9":{"start":{"line":19,"column":12},"end":{"line":19,"column":26}},"10":{"start":{"line":21,"column":12},"end":{"line":21,"column":35}},"11":{"start":{"line":24,"column":8},"end":{"line":24,"column":17}},"12":{"start":{"line":39,"column":0},"end":{"line":47,"column":2}},"13":{"start":{"line":41,"column":8},"end":{"line":41,"column":51}},"14":{"start":{"line":45,"column":8},"end":{"line":45,"column":65}}},"branchMap":{"1":{"line":11,"type":"if","locations":[{"start":{"line":11,"column":8},"end":{"line":11,"column":8}},{"start":{"line":11,"column":8},"end":{"line":11,"column":8}}]},"2":{"line":18,"type":"if","locations":[{"start":{"line":18,"column":8},"end":{"line":18,"column":8}},{"start":{"line":18,"column":8},"end":{"line":18,"column":8}}]}},"code":["(function () { YUI.add('event-mousewheel', function (Y, NAME) {","","/**"," * Adds mousewheel event support"," * @module event"," * @submodule event-mousewheel"," */","var DOM_MOUSE_SCROLL = 'DOMMouseScroll',"," fixArgs = function(args) {"," var a = Y.Array(args, 0, true), target;"," if (Y.UA.gecko) {"," a[0] = DOM_MOUSE_SCROLL;"," target = Y.config.win;"," } else {"," target = Y.config.doc;"," }",""," if (a.length < 3) {"," a[2] = target;"," } else {"," a.splice(2, 0, target);"," }",""," return a;"," };","","/**"," * Mousewheel event. This listener is automatically attached to the"," * correct target, so one should not be supplied. Mouse wheel"," * direction and velocity is stored in the 'wheelDelta' field."," * @event mousewheel"," * @param type {string} 'mousewheel'"," * @param fn {function} the callback to execute"," * @param context optional context object"," * @param args 0..n additional arguments to provide to the listener."," * @return {EventHandle} the detach handle"," * @for YUI"," */","Y.Env.evt.plugins.mousewheel = {"," on: function() {"," return Y.Event._attach(fixArgs(arguments));"," },",""," detach: function() {"," return Y.Event.detach.apply(Y.Event, fixArgs(arguments));"," }","};","","","}, '@VERSION@', {\"requires\": [\"node-base\"]});","","}());"]};
}
var __cov_Xo_bjaLCYmCUa2BefojaXw = __coverage__['build/event-mousewheel/event-mousewheel.js'];
__cov_Xo_bjaLCYmCUa2BefojaXw.s['1']++;YUI.add('event-mousewheel',function(Y,NAME){__cov_Xo_bjaLCYmCUa2BefojaXw.f['1']++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['2']++;var DOM_MOUSE_SCROLL='DOMMouseScroll',fixArgs=function(args){__cov_Xo_bjaLCYmCUa2BefojaXw.f['2']++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['3']++;var a=Y.Array(args,0,true),target;__cov_Xo_bjaLCYmCUa2BefojaXw.s['4']++;if(Y.UA.gecko){__cov_Xo_bjaLCYmCUa2BefojaXw.b['1'][0]++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['5']++;a[0]=DOM_MOUSE_SCROLL;__cov_Xo_bjaLCYmCUa2BefojaXw.s['6']++;target=Y.config.win;}else{__cov_Xo_bjaLCYmCUa2BefojaXw.b['1'][1]++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['7']++;target=Y.config.doc;}__cov_Xo_bjaLCYmCUa2BefojaXw.s['8']++;if(a.length<3){__cov_Xo_bjaLCYmCUa2BefojaXw.b['2'][0]++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['9']++;a[2]=target;}else{__cov_Xo_bjaLCYmCUa2BefojaXw.b['2'][1]++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['10']++;a.splice(2,0,target);}__cov_Xo_bjaLCYmCUa2BefojaXw.s['11']++;return a;};__cov_Xo_bjaLCYmCUa2BefojaXw.s['12']++;Y.Env.evt.plugins.mousewheel={on:function(){__cov_Xo_bjaLCYmCUa2BefojaXw.f['3']++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['13']++;return Y.Event._attach(fixArgs(arguments));},detach:function(){__cov_Xo_bjaLCYmCUa2BefojaXw.f['4']++;__cov_Xo_bjaLCYmCUa2BefojaXw.s['14']++;return Y.Event.detach.apply(Y.Event,fixArgs(arguments));}};},'@VERSION@',{'requires':['node-base']});
| LorenzoBoccaccia/cdnjs | ajax/libs/yui/3.14.1/event-mousewheel/event-mousewheel-coverage.js | JavaScript | mit | 5,034 |
// An Entry consisting of:
//
// "%d %s=%s\n", <length>, <keyword>, <value>
//
// The length is a decimal number, and includes itself and the \n
// \0 does not terminate anything. Only the length terminates the string.
// Numeric values are decimal strings.
module.exports = ExtendedHeader
var Entry = require("./entry.js")
, inherits = require("inherits")
, tar = require("../tar.js")
, numeric = tar.numeric
, keyTrans = { "SCHILY.dev": "dev"
, "SCHILY.ino": "ino"
, "SCHILY.nlink": "nlink" }
function ExtendedHeader () {
Entry.apply(this, arguments)
this.on("data", this._parse)
this.fields = {}
this._position = 0
this._fieldPos = 0
this._state = SIZE
this._sizeBuf = []
this._keyBuf = []
this._valBuf = []
this._size = -1
this._key = ""
}
inherits(ExtendedHeader, Entry)
ExtendedHeader.prototype._parse = parse
var s = 0
, states = ExtendedHeader.states = {}
, SIZE = states.SIZE = s++
, KEY = states.KEY = s++
, VAL = states.VAL = s++
, ERR = states.ERR = s++
Object.keys(states).forEach(function (s) {
states[states[s]] = states[s]
})
states[s] = null
// char code values for comparison
var _0 = "0".charCodeAt(0)
, _9 = "9".charCodeAt(0)
, point = ".".charCodeAt(0)
, a = "a".charCodeAt(0)
, Z = "Z".charCodeAt(0)
, a = "a".charCodeAt(0)
, z = "z".charCodeAt(0)
, space = " ".charCodeAt(0)
, eq = "=".charCodeAt(0)
, cr = "\n".charCodeAt(0)
function parse (c) {
if (this._state === ERR) return
for ( var i = 0, l = c.length
; i < l
; this._position++, this._fieldPos++, i++) {
// console.error("top of loop, size="+this._size)
var b = c[i]
if (this._size >= 0 && this._fieldPos > this._size) {
error(this, "field exceeds length="+this._size)
return
}
switch (this._state) {
case ERR: return
case SIZE:
// console.error("parsing size, b=%d, rest=%j", b, c.slice(i).toString())
if (b === space) {
this._state = KEY
// this._fieldPos = this._sizeBuf.length
this._size = parseInt(new Buffer(this._sizeBuf).toString(), 10)
this._sizeBuf.length = 0
continue
}
if (b < _0 || b > _9) {
error(this, "expected [" + _0 + ".." + _9 + "], got " + b)
return
}
this._sizeBuf.push(b)
continue
case KEY:
// can be any char except =, not > size.
if (b === eq) {
this._state = VAL
this._key = new Buffer(this._keyBuf).toString()
if (keyTrans[this._key]) this._key = keyTrans[this._key]
this._keyBuf.length = 0
continue
}
this._keyBuf.push(b)
continue
case VAL:
// field must end with cr
if (this._fieldPos === this._size - 1) {
// console.error("finished with "+this._key)
if (b !== cr) {
error(this, "expected \\n at end of field")
return
}
var val = new Buffer(this._valBuf).toString()
if (numeric[this._key]) {
val = parseFloat(val)
}
this.fields[this._key] = val
this._valBuf.length = 0
this._state = SIZE
this._size = -1
this._fieldPos = -1
continue
}
this._valBuf.push(b)
continue
}
}
}
function error (me, msg) {
msg = "invalid header: " + msg
+ "\nposition=" + me._position
+ "\nfield position=" + me._fieldPos
me.error(msg)
me.state = ERR
}
| Elvisthacoder/kim-tech | node_modules/sqlite3/node_modules/node-pre-gyp/node_modules/tar-pack/node_modules/tar/lib/extended-header.js | JavaScript | mit | 3,563 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
Persist = _dereq_('../lib/Persist');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Persist":28,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":7,"../lib/Shim.IE8":34}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":27,"./Shared":33}],4:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
'*': function (data) {
return this.$main.call(this, data, {});
},
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Index2d":10,"./IndexBinaryTree":11,"./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Overload":26,"./Path":27,"./ReactorIO":31,"./Shared":33}],6:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {String=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Remove old data
this._data.remove(chainPacket.data.oldData);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":33}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":14,"./Overload":26,"./Shared":33}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":14,"./Overload":26,"./Shared":33}],9:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - rob@irrelon.com
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],10:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":3,"./GeoHash":9,"./Path":27,"./Shared":33}],11:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":27,"./Shared":33}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":27,"./Shared":33}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":33}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":25,"./Shared":33}],15:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],16:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],17:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":26,"./Serialiser":32}],18:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],19:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":26}],20:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":26}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":27,"./Shared":33}],26:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],27:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":33}],28:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the auto flag which determines if the persistence module
* will automatically load data for collections the first time they are
* accessed and save data whenever it changes. This is disabled by
* default.
* @param {Boolean} val Set to true to enable, false to disable
* @returns {*}
*/
Shared.synthesize(Persist.prototype, 'auto', function (val) {
var self = this;
if (val !== undefined) {
if (val) {
// Hook db events
this._db.on('create', function () { self._autoLoad.apply(self, arguments); });
this._db.on('change', function () { self._autoSave.apply(self, arguments); });
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save enabled');
}
} else {
// Un-hook db events
this._db.off('create', this._autoLoad);
this._db.off('change', this._autoSave);
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save disbled');
}
}
}
return this.$super.call(this, val);
});
Persist.prototype._autoLoad = function (obj, objType, name) {
var self = this;
if (typeof obj.load === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name);
}
obj.load(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic load failed:', err);
}
self.emit('load', err, data);
});
} else {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping');
}
}
};
Persist.prototype._autoSave = function (obj, objType, name) {
var self = this;
if (typeof obj.save === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name);
}
obj.save(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic save failed:', err);
}
self.emit('save', err, data);
});
}
};
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); }
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) { callback(err, data, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
//self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) { callback(err, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
/**
* Gets the data that represents this collection for easy storage using
* a third-party method / plugin instead of using the standard persistent
* storage system.
* @param {Function} callback The method to call with the data response.
*/
Collection.prototype.saveCustom = function (callback) {
var self = this,
myData = {},
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.data = {
name: self._db._name + '-' + self._name,
store: data,
tableStats: tableStats
};
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.metaData = {
name: self._db._name + '-' + self._name + '-metaData',
store: data,
tableStats: tableStats
};
callback(false, myData);
} else {
callback(err);
}
});
} else {
callback(err);
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads custom data loaded by a third-party plugin into the collection.
* @param {Object} myData Data object previously saved by using saveCustom()
* @param {Function} callback A callback method to receive notification when
* data has loaded.
*/
Collection.prototype.loadCustom = function (myData, callback) {
var self = this;
if (self._name) {
if (self._db) {
if (myData.data && myData.data.store) {
if (myData.metaData && myData.metaData.store) {
self.decode(myData.data.store, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
self.decode(myData.metaData.store, function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
if (callback) { callback(err, tableStats, metaStats); }
}
} else {
callback(err);
}
});
}
} else {
callback(err);
}
});
} else {
callback('No "metaData" key found in passed object!');
}
} else {
callback('No "data" key found in passed object!');
}
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
Db.prototype.load = new Overload({
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (myData, callback) {
this.$main.call(this, myData, callback);
},
'$main': function (myData, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) {
callback(false);
}
}
} else {
if (callback) {
callback(err);
}
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
if (!myData) {
obj[index].load(loadCallback);
} else {
obj[index].loadCustom(myData, loadCallback);
}
}
}
}
});
Db.prototype.save = new Overload({
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (options, callback) {
this.$main.call(this, options, callback);
},
'$main': function (options, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
if (!options.custom) {
obj[index].save(saveCallback);
} else {
obj[index].saveCustom(saveCallback);
}
}
}
}
});
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":29,"./PersistCrypto":30,"./Shared":33,"async":35,"localforage":71}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":33,"pako":72}],30:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":33,"crypto-js":44}],31:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":33}],32:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],33:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.714',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Tags":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":26}],34:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],35:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":70}],36:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],37:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":38}],38:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],39:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":38}],40:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":38}],41:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":38,"./hmac":43,"./sha1":62}],42:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":37,"./core":38}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":38}],44:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":36,"./cipher-core":37,"./core":38,"./enc-base64":39,"./enc-utf16":40,"./evpkdf":41,"./format-hex":42,"./hmac":43,"./lib-typedarrays":45,"./md5":46,"./mode-cfb":47,"./mode-ctr":49,"./mode-ctr-gladman":48,"./mode-ecb":50,"./mode-ofb":51,"./pad-ansix923":52,"./pad-iso10126":53,"./pad-iso97971":54,"./pad-nopadding":55,"./pad-zeropadding":56,"./pbkdf2":57,"./rabbit":59,"./rabbit-legacy":58,"./rc4":60,"./ripemd160":61,"./sha1":62,"./sha224":63,"./sha256":64,"./sha3":65,"./sha384":66,"./sha512":67,"./tripledes":68,"./x64-core":69}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":38}],46:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":38}],47:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":37,"./core":38}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":37,"./core":38}],49:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":37,"./core":38}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":37,"./core":38}],51:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":37,"./core":38}],52:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":37,"./core":38}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":37,"./core":38}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":37,"./core":38}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":37,"./core":38}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":37,"./core":38}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":38,"./hmac":43,"./sha1":62}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],61:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":38}],62:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":38}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":38,"./sha256":64}],64:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":38}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":38,"./x64-core":69}],66:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":38,"./sha512":67,"./x64-core":69}],67:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":38,"./x64-core":69}],68:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":37,"./core":38,"./enc-base64":39,"./evpkdf":41,"./md5":46}],69:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":38}],70:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],71:[function(_dereq_,module,exports){
(function (process,global){
/*!
localForage -- Offline Storage, Improved
Version 1.3.0
https://mozilla.github.io/localForage
(c) 2013-2015 Mozilla, Apache License 2.0
*/
(function() {
var define, requireModule, _dereq_, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = _dereq_ = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("promise/all",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
var isFunction = __dependency1__.isFunction;
/**
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The return promise
is fulfilled with an array that gives all the values in the order they were
passed in the `promises` array argument.
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for RSVP
@param {Array} promises
@param {String} label
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
*/
function all(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve, reject) {
var results = [], remaining = promises.length,
promise;
if (remaining === 0) {
resolve([]);
}
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function resolveAll(index, value) {
results[index] = value;
if (--remaining === 0) {
resolve(results);
}
}
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && isFunction(promise.then)) {
promise.then(resolver(i), reject);
} else {
resolveAll(i, promise);
}
}
});
}
__exports__.all = all;
});
define("promise/asap",
["exports"],
function(__exports__) {
"use strict";
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
// node
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useSetTimeout() {
return function() {
local.setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0], arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
// If length is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush();
}
}
__exports__.asap = asap;
});
define("promise/config",
["exports"],
function(__exports__) {
"use strict";
var config = {
instrument: false
};
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
__exports__.config = config;
__exports__.configure = configure;
});
define("promise/polyfill",
["./promise","./utils","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*global self*/
var RSVPPromise = __dependency1__.Promise;
var isFunction = __dependency2__.isFunction;
function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = RSVPPromise;
}
}
__exports__.polyfill = polyfill;
});
define("promise/promise",
["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) {
"use strict";
var config = __dependency1__.config;
var configure = __dependency1__.configure;
var objectOrFunction = __dependency2__.objectOrFunction;
var isFunction = __dependency2__.isFunction;
var now = __dependency2__.now;
var all = __dependency3__.all;
var race = __dependency4__.race;
var staticResolve = __dependency5__.resolve;
var staticReject = __dependency6__.reject;
var asap = __dependency7__.asap;
var counter = 0;
config.async = asap; // default async is asap;
function Promise(resolver) {
if (!isFunction(resolver)) {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
if (!(this instanceof Promise)) {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
this._subscribers = [];
invokeResolver(resolver, this);
}
function invokeResolver(resolver, promise) {
function resolvePromise(value) {
resolve(promise, value);
}
function rejectPromise(reason) {
reject(promise, reason);
}
try {
resolver(resolvePromise, rejectPromise);
} catch(e) {
rejectPromise(e);
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
try {
value = callback(detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = detail;
succeeded = true;
}
if (handleThenable(promise, value)) {
return;
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
resolve(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
var PENDING = void 0;
var SEALED = 0;
var FULFILLED = 1;
var REJECTED = 2;
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
}
function publish(promise, settled) {
var child, callback, subscribers = promise._subscribers, detail = promise._detail;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
invokeCallback(settled, child, callback, detail);
}
promise._subscribers = null;
}
Promise.prototype = {
constructor: Promise,
_state: undefined,
_detail: undefined,
_subscribers: undefined,
then: function(onFulfillment, onRejection) {
var promise = this;
var thenPromise = new this.constructor(function() {});
if (this._state) {
var callbacks = arguments;
config.async(function invokePromiseCallback() {
invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
});
} else {
subscribe(this, thenPromise, onFulfillment, onRejection);
}
return thenPromise;
},
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
Promise.all = all;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;
function handleThenable(promise, value) {
var then = null,
resolved;
try {
if (promise === value) {
throw new TypeError("A promises callback cannot return that same promise.");
}
if (objectOrFunction(value)) {
then = value.then;
if (isFunction(then)) {
then.call(value, function(val) {
if (resolved) { return true; }
resolved = true;
if (value !== val) {
resolve(promise, val);
} else {
fulfill(promise, val);
}
}, function(val) {
if (resolved) { return true; }
resolved = true;
reject(promise, val);
});
return true;
}
}
} catch (error) {
if (resolved) { return true; }
reject(promise, error);
return true;
}
return false;
}
function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (!handleThenable(promise, value)) {
fulfill(promise, value);
}
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = value;
config.async(publishFulfillment, promise);
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = reason;
config.async(publishRejection, promise);
}
function publishFulfillment(promise) {
publish(promise, promise._state = FULFILLED);
}
function publishRejection(promise) {
publish(promise, promise._state = REJECTED);
}
__exports__.Promise = Promise;
});
define("promise/race",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
/**
`RSVP.race` allows you to watch a series of promises and act as soon as the
first promise given to the `promises` argument fulfills or rejects.
Example:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 2");
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// result === "promise 2" because it was resolved before promise1
// was resolved.
});
```
`RSVP.race` is deterministic in that only the state of the first completed
promise matters. For example, even if other promises given to the `promises`
array argument are resolved, but the first completed promise has become
rejected before the other promises became fulfilled, the returned promise
will become rejected:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error("promise 2"));
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// Code here never runs because there are rejected promises!
}, function(reason){
// reason.message === "promise2" because promise 2 became rejected before
// promise 1 became fulfilled
});
```
@method race
@for RSVP
@param {Array} promises array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise that becomes fulfilled with the value the first
completed promises is resolved with if the first completed promise was
fulfilled, or rejected with the reason that the first completed promise
was rejected with.
*/
function race(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve, reject) {
var results = [], promise;
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
});
}
__exports__.race = race;
});
define("promise/reject",
["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.reject` returns a promise that will become rejected with the passed
`reason`. `RSVP.reject` is essentially shorthand for the following:
```javascript
var promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = RSVP.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@for RSVP
@param {Any} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become rejected with the given
`reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Promise = this;
return new Promise(function (resolve, reject) {
reject(reason);
});
}
__exports__.reject = reject;
});
define("promise/resolve",
["exports"],
function(__exports__) {
"use strict";
function resolve(value) {
/*jshint validthis:true */
if (value && typeof value === 'object' && value.constructor === this) {
return value;
}
var Promise = this;
return new Promise(function(resolve) {
resolve(value);
});
}
__exports__.resolve = resolve;
});
define("promise/utils",
["exports"],
function(__exports__) {
"use strict";
function objectOrFunction(x) {
return isFunction(x) || (typeof x === "object" && x !== null);
}
function isFunction(x) {
return typeof x === "function";
}
function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
// Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now || function() { return new Date().getTime(); };
__exports__.objectOrFunction = objectOrFunction;
__exports__.isFunction = isFunction;
__exports__.isArray = isArray;
__exports__.now = now;
});
requireModule('promise/polyfill').polyfill();
}());(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["localforage"] = factory();
else
root["localforage"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
(function () {
'use strict';
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'];
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function (self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function () {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB && typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function () {
try {
return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem;
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var LocalForage = (function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
this.INDEXEDDB = DriverType.INDEXEDDB;
this.LOCALSTORAGE = DriverType.LOCALSTORAGE;
this.WEBSQL = DriverType.WEBSQL;
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver);
}
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof options === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
var namingError = new Error('Custom driver name already in use: ' + driverObject._driver);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function (supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
promise.then(callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var self = this;
var getDriverPromise = (function () {
if (isLibraryDriver(driverName)) {
switch (driverName) {
case self.INDEXEDDB:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(1));
});
case self.LOCALSTORAGE:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(2));
});
case self.WEBSQL:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(4));
});
}
} else if (CustomDrivers[driverName]) {
return Promise.resolve(CustomDrivers[driverName]);
}
return Promise.reject(new Error('Driver not found.'));
})();
getDriverPromise.then(callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
});
if (callback && typeof callback === 'function') {
serializerPromise.then(function (result) {
callback(result);
});
}
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
promise.then(callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
})['catch'](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () {
return Promise.resolve();
}) : Promise.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})['catch'](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
});
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
})();
var localForage = new LocalForage();
exports['default'] = localForage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
var dbContexts;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({ status: xhr.status, response: xhr.response });
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function (resolve, reject) {
var blob = _createBlob([''], { type: 'image/png' });
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function () {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function (e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function (res) {
resolve(!!(res && res.type === 'image/png'));
}, function () {
resolve(false);
}).then(function () {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Initialize a singleton container for all running localForages.
if (!dbContexts) {
dbContexts = {};
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null
};
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(this);
// Create an array of readiness of the related localForages.
var readyPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== this) {
// Don't wait for itself...
readyPromises.push(forage.ready()['catch'](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise.all(readyPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k in forages) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise(function (resolve, reject) {
if (dbInfo.db) {
if (upgradeNeeded) {
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = indexedDB.open.apply(indexedDB, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function () {
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
};
});
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void 0) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function (blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function (value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = asyncStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
if (dbInfo.storeName !== self._defaultConfig.storeName) {
dbInfo.keyPrefix += dbInfo.storeName + '/';
}
self._dbInfo = dbInfo;
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = localStorageWrapper;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
(function () {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
exports['default'] = localforageSerializer;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function () {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
});
});
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = webSQLStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":70}],72:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":75,"./utils/strings":76,"./zlib/constants":78,"./zlib/gzheader":81,"./zlib/inflate.js":83,"./zlib/messages":85,"./zlib/zstream":87}],75:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],76:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":75}],77:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],78:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],79:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],80:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],82:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],83:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":75}],85:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],86:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":75}],87:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
| iwdmb/cdnjs | ajax/libs/forerunnerdb/1.3.714/fdb-core+persist.js | JavaScript | mit | 856,444 |
/*! Stellar.js v0.6.2 | Copyright 2013, Mark Dalgleish | http://markdalgleish.com/projects/stellar.js | http://markdalgleish.mit-license.org */
(function(e,t,n,r){function d(t,n){this.element=t,this.options=e.extend({},s,n),this._defaults=s,this._name=i,this.init()}var i="stellar",s={scrollProperty:"scroll",positionProperty:"position",horizontalScrolling:!0,verticalScrolling:!0,horizontalOffset:0,verticalOffset:0,responsive:!1,parallaxBackgrounds:!0,parallaxElements:!0,hideDistantElements:!0,hideElement:function(e){e.hide()},showElement:function(e){e.show()}},o={scroll:{getLeft:function(e){return e.scrollLeft()},setLeft:function(e,t){e.scrollLeft(t)},getTop:function(e){return e.scrollTop()},setTop:function(e,t){e.scrollTop(t)}},position:{getLeft:function(e){return parseInt(e.css("left"),10)*-1},getTop:function(e){return parseInt(e.css("top"),10)*-1}},margin:{getLeft:function(e){return parseInt(e.css("margin-left"),10)*-1},getTop:function(e){return parseInt(e.css("margin-top"),10)*-1}},transform:{getLeft:function(e){var t=getComputedStyle(e[0])[f];return t!=="none"?parseInt(t.match(/(-?[0-9]+)/g)[4],10)*-1:0},getTop:function(e){var t=getComputedStyle(e[0])[f];return t!=="none"?parseInt(t.match(/(-?[0-9]+)/g)[5],10)*-1:0}}},u={position:{setLeft:function(e,t){e.css("left",t)},setTop:function(e,t){e.css("top",t)}},transform:{setPosition:function(e,t,n,r,i){e[0].style[f]="translate3d("+(t-n)+"px, "+(r-i)+"px, 0)"}}},a=function(){var t=/^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/,n=e("script")[0].style,r="",i;for(i in n)if(t.test(i)){r=i.match(t)[0];break}return"WebkitOpacity"in n&&(r="Webkit"),"KhtmlOpacity"in n&&(r="Khtml"),function(e){return r+(r.length>0?e.charAt(0).toUpperCase()+e.slice(1):e)}}(),f=a("transform"),l=e("<div />",{style:"background:#fff"}).css("background-position-x")!==r,c=l?function(e,t,n){e.css({"background-position-x":t,"background-position-y":n})}:function(e,t,n){e.css("background-position",t+" "+n)},h=l?function(e){return[e.css("background-position-x"),e.css("background-position-y")]}:function(e){return e.css("background-position").split(" ")},p=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.oRequestAnimationFrame||t.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)};d.prototype={init:function(){this.options.name=i+"_"+Math.floor(Math.random()*1e9),this._defineElements(),this._defineGetters(),this._defineSetters(),this._handleWindowLoadAndResize(),this._detectViewport(),this.refresh({firstLoad:!0}),this.options.scrollProperty==="scroll"?this._handleScrollEvent():this._startAnimationLoop()},_defineElements:function(){this.element===n.body&&(this.element=t),this.$scrollElement=e(this.element),this.$element=this.element===t?e("body"):this.$scrollElement,this.$viewportElement=this.options.viewportElement!==r?e(this.options.viewportElement):this.$scrollElement[0]===t||this.options.scrollProperty==="scroll"?this.$scrollElement:this.$scrollElement.parent()},_defineGetters:function(){var e=this,t=o[e.options.scrollProperty];this._getScrollLeft=function(){return t.getLeft(e.$scrollElement)},this._getScrollTop=function(){return t.getTop(e.$scrollElement)}},_defineSetters:function(){var t=this,n=o[t.options.scrollProperty],r=u[t.options.positionProperty],i=n.setLeft,s=n.setTop;this._setScrollLeft=typeof i=="function"?function(e){i(t.$scrollElement,e)}:e.noop,this._setScrollTop=typeof s=="function"?function(e){s(t.$scrollElement,e)}:e.noop,this._setPosition=r.setPosition||function(e,n,i,s,o){t.options.horizontalScrolling&&r.setLeft(e,n,i),t.options.verticalScrolling&&r.setTop(e,s,o)}},_handleWindowLoadAndResize:function(){var n=this,r=e(t);n.options.responsive&&r.bind("load."+this.name,function(){n.refresh()}),r.bind("resize."+this.name,function(){n._detectViewport(),n.options.responsive&&n.refresh()})},refresh:function(n){var r=this,i=r._getScrollLeft(),s=r._getScrollTop();(!n||!n.firstLoad)&&this._reset(),this._setScrollLeft(0),this._setScrollTop(0),this._setOffsets(),this._findParticles(),this._findBackgrounds(),n&&n.firstLoad&&/WebKit/.test(navigator.userAgent)&&e(t).load(function(){var e=r._getScrollLeft(),t=r._getScrollTop();r._setScrollLeft(e+1),r._setScrollTop(t+1),r._setScrollLeft(e),r._setScrollTop(t)}),this._setScrollLeft(i),this._setScrollTop(s)},_detectViewport:function(){var e=this.$viewportElement.offset(),t=e!==null&&e!==r;this.viewportWidth=this.$viewportElement.width(),this.viewportHeight=this.$viewportElement.height(),this.viewportOffsetTop=t?e.top:0,this.viewportOffsetLeft=t?e.left:0},_findParticles:function(){var t=this,n=this._getScrollLeft(),i=this._getScrollTop();if(this.particles!==r)for(var s=this.particles.length-1;s>=0;s--)this.particles[s].$element.data("stellar-elementIsActive",r);this.particles=[];if(!this.options.parallaxElements)return;this.$element.find("[data-stellar-ratio]").each(function(n){var i=e(this),s,o,u,a,f,l,c,h,p,d=0,v=0,m=0,g=0;if(!i.data("stellar-elementIsActive"))i.data("stellar-elementIsActive",this);else if(i.data("stellar-elementIsActive")!==this)return;t.options.showElement(i),i.data("stellar-startingLeft")?(i.css("left",i.data("stellar-startingLeft")),i.css("top",i.data("stellar-startingTop"))):(i.data("stellar-startingLeft",i.css("left")),i.data("stellar-startingTop",i.css("top"))),u=i.position().left,a=i.position().top,f=i.css("margin-left")==="auto"?0:parseInt(i.css("margin-left"),10),l=i.css("margin-top")==="auto"?0:parseInt(i.css("margin-top"),10),h=i.offset().left-f,p=i.offset().top-l,i.parents().each(function(){var t=e(this);if(t.data("stellar-offset-parent")===!0)return d=m,v=g,c=t,!1;m+=t.position().left,g+=t.position().top}),s=i.data("stellar-horizontal-offset")!==r?i.data("stellar-horizontal-offset"):c!==r&&c.data("stellar-horizontal-offset")!==r?c.data("stellar-horizontal-offset"):t.horizontalOffset,o=i.data("stellar-vertical-offset")!==r?i.data("stellar-vertical-offset"):c!==r&&c.data("stellar-vertical-offset")!==r?c.data("stellar-vertical-offset"):t.verticalOffset,t.particles.push({$element:i,$offsetParent:c,isFixed:i.css("position")==="fixed",horizontalOffset:s,verticalOffset:o,startingPositionLeft:u,startingPositionTop:a,startingOffsetLeft:h,startingOffsetTop:p,parentOffsetLeft:d,parentOffsetTop:v,stellarRatio:i.data("stellar-ratio")!==r?i.data("stellar-ratio"):1,width:i.outerWidth(!0),height:i.outerHeight(!0),isHidden:!1})})},_findBackgrounds:function(){var t=this,n=this._getScrollLeft(),i=this._getScrollTop(),s;this.backgrounds=[];if(!this.options.parallaxBackgrounds)return;s=this.$element.find("[data-stellar-background-ratio]"),this.$element.data("stellar-background-ratio")&&(s=s.add(this.$element)),s.each(function(){var s=e(this),o=h(s),u,a,f,l,p,d,v,m,g,y=0,b=0,w=0,E=0;if(!s.data("stellar-backgroundIsActive"))s.data("stellar-backgroundIsActive",this);else if(s.data("stellar-backgroundIsActive")!==this)return;s.data("stellar-backgroundStartingLeft")?c(s,s.data("stellar-backgroundStartingLeft"),s.data("stellar-backgroundStartingTop")):(s.data("stellar-backgroundStartingLeft",o[0]),s.data("stellar-backgroundStartingTop",o[1])),p=s.css("margin-left")==="auto"?0:parseInt(s.css("margin-left"),10),d=s.css("margin-top")==="auto"?0:parseInt(s.css("margin-top"),10),v=s.offset().left-p-n,m=s.offset().top-d-i,s.parents().each(function(){var t=e(this);if(t.data("stellar-offset-parent")===!0)return y=w,b=E,g=t,!1;w+=t.position().left,E+=t.position().top}),u=s.data("stellar-horizontal-offset")!==r?s.data("stellar-horizontal-offset"):g!==r&&g.data("stellar-horizontal-offset")!==r?g.data("stellar-horizontal-offset"):t.horizontalOffset,a=s.data("stellar-vertical-offset")!==r?s.data("stellar-vertical-offset"):g!==r&&g.data("stellar-vertical-offset")!==r?g.data("stellar-vertical-offset"):t.verticalOffset,t.backgrounds.push({$element:s,$offsetParent:g,isFixed:s.css("background-attachment")==="fixed",horizontalOffset:u,verticalOffset:a,startingValueLeft:o[0],startingValueTop:o[1],startingBackgroundPositionLeft:isNaN(parseInt(o[0],10))?0:parseInt(o[0],10),startingBackgroundPositionTop:isNaN(parseInt(o[1],10))?0:parseInt(o[1],10),startingPositionLeft:s.position().left,startingPositionTop:s.position().top,startingOffsetLeft:v,startingOffsetTop:m,parentOffsetLeft:y,parentOffsetTop:b,stellarRatio:s.data("stellar-background-ratio")===r?1:s.data("stellar-background-ratio")})})},_reset:function(){var e,t,n,r,i;for(i=this.particles.length-1;i>=0;i--)e=this.particles[i],t=e.$element.data("stellar-startingLeft"),n=e.$element.data("stellar-startingTop"),this._setPosition(e.$element,t,t,n,n),this.options.showElement(e.$element),e.$element.data("stellar-startingLeft",null).data("stellar-elementIsActive",null).data("stellar-backgroundIsActive",null);for(i=this.backgrounds.length-1;i>=0;i--)r=this.backgrounds[i],r.$element.data("stellar-backgroundStartingLeft",null).data("stellar-backgroundStartingTop",null),c(r.$element,r.startingValueLeft,r.startingValueTop)},destroy:function(){this._reset(),this.$scrollElement.unbind("resize."+this.name).unbind("scroll."+this.name),this._animationLoop=e.noop,e(t).unbind("load."+this.name).unbind("resize."+this.name)},_setOffsets:function(){var n=this,r=e(t);r.unbind("resize.horizontal-"+this.name).unbind("resize.vertical-"+this.name),typeof this.options.horizontalOffset=="function"?(this.horizontalOffset=this.options.horizontalOffset(),r.bind("resize.horizontal-"+this.name,function(){n.horizontalOffset=n.options.horizontalOffset()})):this.horizontalOffset=this.options.horizontalOffset,typeof this.options.verticalOffset=="function"?(this.verticalOffset=this.options.verticalOffset(),r.bind("resize.vertical-"+this.name,function(){n.verticalOffset=n.options.verticalOffset()})):this.verticalOffset=this.options.verticalOffset},_repositionElements:function(){var e=this._getScrollLeft(),t=this._getScrollTop(),n,r,i,s,o,u,a,f=!0,l=!0,h,p,d,v,m;if(this.currentScrollLeft===e&&this.currentScrollTop===t&&this.currentWidth===this.viewportWidth&&this.currentHeight===this.viewportHeight)return;this.currentScrollLeft=e,this.currentScrollTop=t,this.currentWidth=this.viewportWidth,this.currentHeight=this.viewportHeight;for(m=this.particles.length-1;m>=0;m--)i=this.particles[m],s=i.isFixed?1:0,this.options.horizontalScrolling?(h=(e+i.horizontalOffset+this.viewportOffsetLeft+i.startingPositionLeft-i.startingOffsetLeft+i.parentOffsetLeft)*-(i.stellarRatio+s-1)+i.startingPositionLeft,d=h-i.startingPositionLeft+i.startingOffsetLeft):(h=i.startingPositionLeft,d=i.startingOffsetLeft),this.options.verticalScrolling?(p=(t+i.verticalOffset+this.viewportOffsetTop+i.startingPositionTop-i.startingOffsetTop+i.parentOffsetTop)*-(i.stellarRatio+s-1)+i.startingPositionTop,v=p-i.startingPositionTop+i.startingOffsetTop):(p=i.startingPositionTop,v=i.startingOffsetTop),this.options.hideDistantElements&&(l=!this.options.horizontalScrolling||d+i.width>(i.isFixed?0:e)&&d<(i.isFixed?0:e)+this.viewportWidth+this.viewportOffsetLeft,f=!this.options.verticalScrolling||v+i.height>(i.isFixed?0:t)&&v<(i.isFixed?0:t)+this.viewportHeight+this.viewportOffsetTop),l&&f?(i.isHidden&&(this.options.showElement(i.$element),i.isHidden=!1),this._setPosition(i.$element,h,i.startingPositionLeft,p,i.startingPositionTop)):i.isHidden||(this.options.hideElement(i.$element),i.isHidden=!0);for(m=this.backgrounds.length-1;m>=0;m--)o=this.backgrounds[m],s=o.isFixed?0:1,u=this.options.horizontalScrolling?(e+o.horizontalOffset-this.viewportOffsetLeft-o.startingOffsetLeft+o.parentOffsetLeft-o.startingBackgroundPositionLeft)*(s-o.stellarRatio)+"px":o.startingValueLeft,a=this.options.verticalScrolling?(t+o.verticalOffset-this.viewportOffsetTop-o.startingOffsetTop+o.parentOffsetTop-o.startingBackgroundPositionTop)*(s-o.stellarRatio)+"px":o.startingValueTop,c(o.$element,u,a)},_handleScrollEvent:function(){var e=this,t=!1,n=function(){e._repositionElements(),t=!1},r=function(){t||(p(n),t=!0)};this.$scrollElement.bind("scroll."+this.name,r),r()},_startAnimationLoop:function(){var e=this;this._animationLoop=function(){p(e._animationLoop),e._repositionElements()},this._animationLoop()}},e.fn[i]=function(t){var n=arguments;if(t===r||typeof t=="object")return this.each(function(){e.data(this,"plugin_"+i)||e.data(this,"plugin_"+i,new d(this,t))});if(typeof t=="string"&&t[0]!=="_"&&t!=="init")return this.each(function(){var r=e.data(this,"plugin_"+i);r instanceof d&&typeof r[t]=="function"&&r[t].apply(r,Array.prototype.slice.call(n,1)),t==="destroy"&&e.data(this,"plugin_"+i,null)})},e[i]=function(n){var r=e(t);return r.stellar.apply(r,Array.prototype.slice.call(arguments,0))},e[i].scrollProperty=o,e[i].positionProperty=u,t.Stellar=d})(jQuery,this,document); | abutsa/jpv0 | assets/themes/canvas/js/plugins/jquery.parallax.js | JavaScript | mit | 12,637 |
/*!
* # Semantic UI 2.2.3 - Input
* http://github.com/semantic-org/semantic-ui/
*
*
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
/*******************************
Standard
*******************************/
/*--------------------
Inputs
---------------------*/
.ui.input {
position: relative;
font-weight: normal;
font-style: normal;
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
color: rgba(0, 0, 0, 0.87);
}
.ui.input input {
margin: 0em;
max-width: 100%;
-webkit-box-flex: 1;
-webkit-flex: 1 0 auto;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
outline: none;
-webkit-tap-highlight-color: rgba(255, 255, 255, 0);
text-align: left;
line-height: 1.2142em;
font-family: 'Lato', 'Helvetica Neue', Arial, Helvetica, sans-serif;
padding: 0.67861429em 1em;
background: #FFFFFF;
border: 1px solid rgba(34, 36, 38, 0.15);
color: rgba(0, 0, 0, 0.87);
border-radius: 0.28571429rem;
-webkit-transition: box-shadow 0.1s ease, border-color 0.1s ease;
transition: box-shadow 0.1s ease, border-color 0.1s ease;
box-shadow: none;
}
/*--------------------
Placeholder
---------------------*/
/* browsers require these rules separate */
.ui.input input::-webkit-input-placeholder {
color: rgba(191, 191, 191, 0.87);
}
.ui.input input::-moz-placeholder {
color: rgba(191, 191, 191, 0.87);
}
.ui.input input:-ms-input-placeholder {
color: rgba(191, 191, 191, 0.87);
}
/*******************************
States
*******************************/
/*--------------------
Disabled
---------------------*/
.ui.disabled.input,
.ui.input input[disabled] {
opacity: 0.45;
}
.ui.disabled.input input,
.ui.input input[disabled] {
pointer-events: none;
}
/*--------------------
Active
---------------------*/
.ui.input input:active,
.ui.input.down input {
border-color: rgba(0, 0, 0, 0.3);
background: #FAFAFA;
color: rgba(0, 0, 0, 0.87);
box-shadow: none;
}
/*--------------------
Loading
---------------------*/
.ui.loading.loading.input > i.icon:before {
position: absolute;
content: '';
top: 50%;
left: 50%;
margin: -0.64285714em 0em 0em -0.64285714em;
width: 1.28571429em;
height: 1.28571429em;
border-radius: 500rem;
border: 0.2em solid rgba(0, 0, 0, 0.1);
}
.ui.loading.loading.input > i.icon:after {
position: absolute;
content: '';
top: 50%;
left: 50%;
margin: -0.64285714em 0em 0em -0.64285714em;
width: 1.28571429em;
height: 1.28571429em;
-webkit-animation: button-spin 0.6s linear;
animation: button-spin 0.6s linear;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
border-radius: 500rem;
border-color: #767676 transparent transparent;
border-style: solid;
border-width: 0.2em;
box-shadow: 0px 0px 0px 1px transparent;
}
/*--------------------
Focus
---------------------*/
.ui.input.focus input,
.ui.input input:focus {
border-color: #85B7D9;
background: #FFFFFF;
color: rgba(0, 0, 0, 0.8);
box-shadow: none;
}
.ui.input.focus input::-webkit-input-placeholder,
.ui.input input:focus::-webkit-input-placeholder {
color: rgba(115, 115, 115, 0.87);
}
.ui.input.focus input::-moz-placeholder,
.ui.input input:focus::-moz-placeholder {
color: rgba(115, 115, 115, 0.87);
}
.ui.input.focus input:-ms-input-placeholder,
.ui.input input:focus:-ms-input-placeholder {
color: rgba(115, 115, 115, 0.87);
}
/*--------------------
Error
---------------------*/
.ui.input.error input {
background-color: #FFF6F6;
border-color: #E0B4B4;
color: #9F3A38;
box-shadow: none;
}
/* Error Placeholder */
.ui.input.error input::-webkit-input-placeholder {
color: #e7bdbc;
}
.ui.input.error input::-moz-placeholder {
color: #e7bdbc;
}
.ui.input.error input:-ms-input-placeholder {
color: #e7bdbc !important;
}
/* Focused Error Placeholder */
.ui.input.error input:focus::-webkit-input-placeholder {
color: #da9796;
}
.ui.input.error input:focus::-moz-placeholder {
color: #da9796;
}
.ui.input.error input:focus:-ms-input-placeholder {
color: #da9796 !important;
}
/*******************************
Variations
*******************************/
/*--------------------
Transparent
---------------------*/
.ui.transparent.input input {
border-color: transparent !important;
background-color: transparent !important;
padding: 0em !important;
box-shadow: none !important;
}
/* Transparent Icon */
.ui.transparent.icon.input > i.icon {
width: 1.1em;
}
.ui.transparent.icon.input > input {
padding-left: 0em !important;
padding-right: 2em !important;
}
.ui.transparent[class*="left icon"].input > input {
padding-left: 2em !important;
padding-right: 0em !important;
}
/* Transparent Inverted */
.ui.transparent.inverted.input {
color: #FFFFFF;
}
.ui.transparent.inverted.input input {
color: inherit;
}
.ui.transparent.inverted.input input::-webkit-input-placeholder {
color: rgba(255, 255, 255, 0.5);
}
.ui.transparent.inverted.input input::-moz-placeholder {
color: rgba(255, 255, 255, 0.5);
}
.ui.transparent.inverted.input input:-ms-input-placeholder {
color: rgba(255, 255, 255, 0.5);
}
/*--------------------
Icon
---------------------*/
.ui.icon.input > i.icon {
cursor: default;
position: absolute;
line-height: 1;
text-align: center;
top: 0px;
right: 0px;
margin: 0em;
height: 100%;
width: 2.67142857em;
opacity: 0.5;
border-radius: 0em 0.28571429rem 0.28571429rem 0em;
-webkit-transition: opacity 0.3s ease;
transition: opacity 0.3s ease;
}
.ui.icon.input > i.icon:not(.link) {
pointer-events: none;
}
.ui.icon.input input {
padding-right: 2.67142857em !important;
}
.ui.icon.input > i.icon:before,
.ui.icon.input > i.icon:after {
left: 0;
position: absolute;
text-align: center;
top: 50%;
width: 100%;
margin-top: -0.5em;
}
.ui.icon.input > i.link.icon {
cursor: pointer;
}
.ui.icon.input > i.circular.icon {
top: 0.35em;
right: 0.5em;
}
/* Left Icon Input */
.ui[class*="left icon"].input > i.icon {
right: auto;
left: 1px;
border-radius: 0.28571429rem 0em 0em 0.28571429rem;
}
.ui[class*="left icon"].input > i.circular.icon {
right: auto;
left: 0.5em;
}
.ui[class*="left icon"].input > input {
padding-left: 2.67142857em !important;
padding-right: 1em !important;
}
/* Focus */
.ui.icon.input > input:focus ~ i.icon {
opacity: 1;
}
/*--------------------
Labeled
---------------------*/
/* Adjacent Label */
.ui.labeled.input > .label {
-webkit-box-flex: 0;
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
margin: 0;
font-size: 1em;
}
.ui.labeled.input > .label:not(.corner) {
padding-top: 0.78571429em;
padding-bottom: 0.78571429em;
}
/* Regular Label on Left */
.ui.labeled.input:not([class*="corner labeled"]) .label:first-child {
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
}
.ui.labeled.input:not([class*="corner labeled"]) .label:first-child + input {
border-top-left-radius: 0px;
border-bottom-left-radius: 0px;
border-left-color: transparent;
}
.ui.labeled.input:not([class*="corner labeled"]) .label:first-child + input:focus {
border-left-color: #85B7D9;
}
/* Regular Label on Right */
.ui[class*="right labeled"].input input {
border-top-right-radius: 0px !important;
border-bottom-right-radius: 0px !important;
border-right-color: transparent !important;
}
.ui[class*="right labeled"].input input + .label {
border-top-left-radius: 0px;
border-bottom-left-radius: 0px;
}
.ui[class*="right labeled"].input input:focus {
border-right-color: #85B7D9 !important;
}
/* Corner Label */
.ui.labeled.input .corner.label {
top: 1px;
right: 1px;
font-size: 0.64285714em;
border-radius: 0em 0.28571429rem 0em 0em;
}
/* Spacing with corner label */
.ui[class*="corner labeled"]:not([class*="left corner labeled"]).labeled.input input {
padding-right: 2.5em !important;
}
.ui[class*="corner labeled"].icon.input:not([class*="left corner labeled"]) > input {
padding-right: 3.25em !important;
}
.ui[class*="corner labeled"].icon.input:not([class*="left corner labeled"]) > .icon {
margin-right: 1.25em;
}
/* Left Labeled */
.ui[class*="left corner labeled"].labeled.input input {
padding-left: 2.5em !important;
}
.ui[class*="left corner labeled"].icon.input > input {
padding-left: 3.25em !important;
}
.ui[class*="left corner labeled"].icon.input > .icon {
margin-left: 1.25em;
}
/* Corner Label Position */
.ui.input > .ui.corner.label {
top: 1px;
right: 1px;
}
.ui.input > .ui.left.corner.label {
right: auto;
left: 1px;
}
/*--------------------
Action
---------------------*/
.ui.action.input > .button,
.ui.action.input > .buttons {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-flex: 0;
-webkit-flex: 0 0 auto;
-ms-flex: 0 0 auto;
flex: 0 0 auto;
}
.ui.action.input > .button,
.ui.action.input > .buttons > .button {
padding-top: 0.78571429em;
padding-bottom: 0.78571429em;
margin: 0;
}
/* Button on Right */
.ui.action.input:not([class*="left action"]) > input {
border-top-right-radius: 0px !important;
border-bottom-right-radius: 0px !important;
border-right-color: transparent !important;
}
.ui.action.input:not([class*="left action"]) > .dropdown:not(:first-child),
.ui.action.input:not([class*="left action"]) > .button:not(:first-child),
.ui.action.input:not([class*="left action"]) > .buttons:not(:first-child) > .button {
border-radius: 0px;
}
.ui.action.input:not([class*="left action"]) > .dropdown:last-child,
.ui.action.input:not([class*="left action"]) > .button:last-child,
.ui.action.input:not([class*="left action"]) > .buttons:last-child > .button {
border-radius: 0px 0.28571429rem 0.28571429rem 0px;
}
/* Input Focus */
.ui.action.input:not([class*="left action"]) input:focus {
border-right-color: #85B7D9 !important;
}
/* Button on Left */
.ui[class*="left action"].input > input {
border-top-left-radius: 0px !important;
border-bottom-left-radius: 0px !important;
border-left-color: transparent !important;
}
.ui[class*="left action"].input > .dropdown,
.ui[class*="left action"].input > .button,
.ui[class*="left action"].input > .buttons > .button {
border-radius: 0px;
}
.ui[class*="left action"].input > .dropdown:first-child,
.ui[class*="left action"].input > .button:first-child,
.ui[class*="left action"].input > .buttons:first-child > .button {
border-radius: 0.28571429rem 0px 0px 0.28571429rem;
}
/* Input Focus */
.ui[class*="left action"].input > input:focus {
border-left-color: #85B7D9 !important;
}
/*--------------------
Inverted
---------------------*/
/* Standard */
.ui.inverted.input input {
border: none;
}
/*--------------------
Fluid
---------------------*/
.ui.fluid.input {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.ui.fluid.input > input {
width: 0px !important;
}
/*--------------------
Size
---------------------*/
.ui.mini.input {
font-size: 0.78571429em;
}
.ui.small.input {
font-size: 0.92857143em;
}
.ui.input {
font-size: 1em;
}
.ui.large.input {
font-size: 1.14285714em;
}
.ui.big.input {
font-size: 1.28571429em;
}
.ui.huge.input {
font-size: 1.42857143em;
}
.ui.massive.input {
font-size: 1.71428571em;
}
/*******************************
Theme Overrides
*******************************/
/*******************************
Site Overrides
*******************************/
| tusharsoni08/matrix | public/semantic/components/input.css | CSS | mit | 11,820 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":6,"../lib/Core":7,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":33,"./Shared":39}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":33,"./Shared":39}],4:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
'*': function (data) {
return this.$main.call(this, data, {});
},
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],6:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {String=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Remove old data
this._data.remove(chainPacket.data.oldData);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":39}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance or returns an existing
* instance if one already exists with the passed name.
* @func document
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.document = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof FdbDocument) {
if (name.state() !== 'droppped') {
return name;
} else {
name = name.name();
}
}
if (this._document && this._document[name]) {
return this._document[name];
}
this._document = this._document || {};
this._document[name] = new FdbDocument(name).db(this);
self.emit('create', self._document[name], 'document', name);
return this._document[name];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":5,"./Shared":39}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - rob@irrelon.com
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
delete this._listeners;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener);
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy,
this._options
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
sData,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
if (xAxis.categories) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
} else {
seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]);
}
}
sData = {
name: seriesName,
data: seriesValues
};
if (options.seriesOptions) {
for (k in options.seriesOptions) {
if (options.seriesOptions.hasOwnProperty(k)) {
sData[k] = options.seriesOptions[k];
}
}
}
seriesData.push(sData);
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () {
self._changeListener.apply(self, arguments);
});
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () {
self.drop.apply(self);
});
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if (typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy,
self._options
);
if (seriesData.xAxis.categories) {
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
}
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) {
callback(false, true);
}
delete this._listeners;
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via selector.
* @func lineChart
* @memberof Highchart
* @param {String} selector The chart selector.
* @returns {*}
*/
'string': function (selector) {
return this._highcharts[selector];
},
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":31,"./Shared":39}],13:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":33,"./Shared":39}],16:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":39}],17:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":30,"./Shared":39}],18:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],19:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":31,"./Serialiser":38}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":31}],23:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
if (sourceType === 'object' && source === null) {
sourceType = 'null';
}
if (testType === 'object' && test === null) {
testType = 'null';
}
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number' || sourceType === 'null' || testType === 'null') {
// Number or null comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
self.triggerStack = {};
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
/**
* Tells the current instance to fire or ignore all triggers whether they
* are enabled or not.
* @param {Boolean} val Set to true to ignore triggers or false to not
* ignore them.
* @returns {*}
*/
ignoreTriggers: function (val) {
if (val !== undefined) {
this._ignoreTriggers = val;
return this;
}
return this._ignoreTriggers;
},
/**
* Generates triggers that fire in the after phase for all CRUD ops
* that automatically transform data back and forth and keep both
* import and export collections in sync with each other.
* @param {String} id The unique id for this link IO.
* @param {Object} ioData The settings for the link IO.
*/
addLinkIO: function (id, ioData) {
var self = this,
matchAll,
exportData,
importData,
exportTriggerMethod,
importTriggerMethod,
exportTo,
importFrom,
allTypes,
i;
// Store the linkIO
self._linkIO = self._linkIO || {};
self._linkIO[id] = ioData;
exportData = ioData['export'];
importData = ioData['import'];
if (exportData) {
exportTo = self.db().collection(exportData.to);
}
if (importData) {
importFrom = self.db().collection(importData.from);
}
allTypes = [
self.TYPE_INSERT,
self.TYPE_UPDATE,
self.TYPE_REMOVE
];
matchAll = function (data, callback) {
// Match all
callback(false, true);
};
if (exportData) {
// Check for export match method
if (!exportData.match) {
// No match method found, use the match all method
exportData.match = matchAll;
}
// Check for export types
if (!exportData.types) {
exportData.types = allTypes;
}
exportTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
exportData.match(newDoc, function (err, doExport) {
if (doExport) {
// Get data to upsert (if any)
exportData.data(newDoc, operation.type, function (err, data, callback) {
if (data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
exportTo.upsert(data, callback);
} else {
// Do remove
exportTo.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (importData) {
// Check for import match method
if (!importData.match) {
// No match method found, use the match all method
importData.match = matchAll;
}
// Check for import types
if (!importData.types) {
importData.types = allTypes;
}
importTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
importData.match(newDoc, function (err, doExport) {
if (doExport) {
// Get data to upsert (if any)
importData.data(newDoc, operation.type, function (err, data, callback) {
if (data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
self.upsert(data, callback);
} else {
// Do remove
self.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod);
}
}
if (importData) {
for (i = 0; i < importData.types.length; i++) {
importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod);
}
}
},
/**
* Removes a previously added link IO via it's ID.
* @param {String} id The id of the link IO to remove.
* @returns {boolean} True if successful, false if the link IO
* was not found.
*/
removeLinkIO: function (id) {
var self = this,
linkIO = self._linkIO[id],
exportData,
importData,
importFrom,
i;
if (linkIO) {
exportData = linkIO['export'];
importData = linkIO['import'];
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER);
}
}
if (importData) {
importFrom = self.db().collection(importData.from);
for (i = 0; i < importData.types.length; i++) {
importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER);
}
}
delete self._linkIO[id];
return true;
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response,
typeName,
phaseName;
if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (self.debug()) {
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Check if the trigger is already in the stack, if it is,
// don't fire it again (this is so we avoid infinite loops
// where a trigger triggers another trigger which calls this
// one and so on)
if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) {
// The trigger is already in the stack, do not fire the trigger again
if (self.debug()) {
console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!');
}
continue;
}
// Add the trigger to the stack so we don't go down an endless
// trigger loop
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = true;
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Remove the trigger from the stack
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = false;
// Check the response for a non-expected result (anything other than
// [undefined, true or false] is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],28:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":39}],29:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
delete this._listeners;
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":5,"./CollectionGroup":6,"./Shared":39}],30:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":33,"./Shared":39}],31:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],32:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
}
return true;
};
Db.prototype.overview = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof Overview) {
return name;
}
if (this._overview && this._overview[name]) {
return this._overview[name];
}
this._overview = this._overview || {};
this._overview[name] = new Overview(name).db(this);
self.emit('create', self._overview[name], 'overview', name);
return this._overview[name];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":5,"./Document":9,"./Shared":39}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":39}],34:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the auto flag which determines if the persistence module
* will automatically load data for collections the first time they are
* accessed and save data whenever it changes. This is disabled by
* default.
* @param {Boolean} val Set to true to enable, false to disable
* @returns {*}
*/
Shared.synthesize(Persist.prototype, 'auto', function (val) {
var self = this;
if (val !== undefined) {
if (val) {
// Hook db events
this._db.on('create', function () { self._autoLoad.apply(self, arguments); });
this._db.on('change', function () { self._autoSave.apply(self, arguments); });
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save enabled');
}
} else {
// Un-hook db events
this._db.off('create', this._autoLoad);
this._db.off('change', this._autoSave);
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save disbled');
}
}
}
return this.$super.call(this, val);
});
Persist.prototype._autoLoad = function (obj, objType, name) {
var self = this;
if (typeof obj.load === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name);
}
obj.load(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic load failed:', err);
}
self.emit('load', err, data);
});
} else {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping');
}
}
};
Persist.prototype._autoSave = function (obj, objType, name) {
var self = this;
if (typeof obj.save === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name);
}
obj.save(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic save failed:', err);
}
self.emit('save', err, data);
});
}
};
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); }
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) { callback(err, data, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
//self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) { callback(err, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
/**
* Gets the data that represents this collection for easy storage using
* a third-party method / plugin instead of using the standard persistent
* storage system.
* @param {Function} callback The method to call with the data response.
*/
Collection.prototype.saveCustom = function (callback) {
var self = this,
myData = {},
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.data = {
name: self._db._name + '-' + self._name,
store: data,
tableStats: tableStats
};
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.metaData = {
name: self._db._name + '-' + self._name + '-metaData',
store: data,
tableStats: tableStats
};
callback(false, myData);
} else {
callback(err);
}
});
} else {
callback(err);
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads custom data loaded by a third-party plugin into the collection.
* @param {Object} myData Data object previously saved by using saveCustom()
* @param {Function} callback A callback method to receive notification when
* data has loaded.
*/
Collection.prototype.loadCustom = function (myData, callback) {
var self = this;
if (self._name) {
if (self._db) {
if (myData.data && myData.data.store) {
if (myData.metaData && myData.metaData.store) {
self.decode(myData.data.store, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
self.decode(myData.metaData.store, function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
if (callback) { callback(err, tableStats, metaStats); }
}
} else {
callback(err);
}
});
}
} else {
callback(err);
}
});
} else {
callback('No "metaData" key found in passed object!');
}
} else {
callback('No "data" key found in passed object!');
}
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
Db.prototype.load = new Overload({
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (myData, callback) {
this.$main.call(this, myData, callback);
},
'$main': function (myData, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) {
callback(false);
}
}
} else {
if (callback) {
callback(err);
}
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
if (!myData) {
obj[index].load(loadCallback);
} else {
obj[index].loadCustom(myData, loadCallback);
}
}
}
}
});
Db.prototype.save = new Overload({
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (options, callback) {
this.$main.call(this, options, callback);
},
'$main': function (options, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
if (!options.custom) {
obj[index].save(saveCallback);
} else {
obj[index].saveCustom(saveCallback);
}
}
}
}
});
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":41,"localforage":76}],35:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":39,"pako":77}],36:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":39,"crypto-js":50}],37:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":39}],38:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],39:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.737',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload'),
Path,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.Matching');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Path = Shared.modules.Path;
sharedPathSolver = new Path();
View.prototype.init = function (name, query, options) {
var self = this;
this.sharedPathSolver = sharedPathSolver;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._data = new Collection(this.name() + '_internal');
};
/**
* This reactor IO node is given data changes from source data and
* then acts as a firewall process between the source and view data.
* Data needs to meet the requirements this IO node imposes before
* the data is passed down the reactor chain (to the view). This
* allows us to intercept data changes from the data source and act
* on them such as applying transforms, checking the data matches
* the view's query, applying joins to the data etc before sending it
* down the reactor chain via the this.chainSend() calls.
*
* Update packets are especially complex to handle because an update
* on the underlying source data could translate into an insert,
* update or remove call on the view. Take a scenario where the view's
* query limits the data see from the source. If the source data is
* updated and the data now falls inside the view's query limitations
* the data is technically now an insert on the view, not an update.
* The same is true in reverse where the update becomes a remove. If
* the updated data already exists in the view and will still exist
* after the update operation then the update can remain an update.
* @param {Object} chainPacket The chain reactor packet representing the
* data operation that has just been processed on the source data.
* @param {View} self The reference to the view we are operating for.
* @private
*/
View.prototype._handleChainIO = function (chainPacket, self) {
var type = chainPacket.type,
hasActiveJoin,
hasActiveQuery,
hasTransformIn,
sharedData;
// NOTE: "self" in this context is the view instance.
// NOTE: "this" in this context is the ReactorIO node sitting in
// between the source (sender) and the destination (listener) and
// in this case the source is the view's "from" data source and the
// destination is the view's _data collection. This means
// that "this.chainSend()" is asking the ReactorIO node to send the
// packet on to the destination listener.
// EARLY EXIT: Check that the packet is not a CRUD operation
if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') {
// This packet is NOT a CRUD operation packet so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We only need to check packets under three conditions
// 1) We have a limiting query on the view "active query",
// 2) We have a query options with a $join clause on the view "active join"
// 3) We have a transformIn operation registered on the view.
// If none of these conditions exist we can just allow the chain
// packet to proceed as normal
hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join);
hasActiveQuery = Boolean(self._querySettings.query);
hasTransformIn = self._data._transformIn !== undefined;
// EARLY EXIT: Check for any complex operation flags and if none
// exist, send the packet on and exit early
if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) {
// We don't have any complex operation flags so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We have either an active query, active join or a transformIn
// function registered on the view
// We create a shared data object here so that the disparate method
// calls can share data with each other via this object whilst
// still remaining separate methods to keep code relatively clean.
sharedData = {
dataArr: [],
removeArr: []
};
// Check the packet type to get the data arrays to work on
if (chainPacket.type === 'insert') {
// Check if the insert data is an array
if (chainPacket.data.dataSet instanceof Array) {
// Use the insert data array
sharedData.dataArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single insert object
sharedData.dataArr = [chainPacket.data.dataSet];
}
} else if (chainPacket.type === 'update') {
// Use the dataSet array
sharedData.dataArr = chainPacket.data.dataSet;
} else if (chainPacket.type === 'remove') {
if (chainPacket.data.dataSet instanceof Array) {
// Use the remove data array
sharedData.removeArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single remove object
sharedData.removeArr = [chainPacket.data.dataSet];
}
}
// Safety check
if (!(sharedData.dataArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!');
sharedData.dataArr = [];
}
if (!(sharedData.removeArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!');
sharedData.removeArr = [];
}
// We need to operate in this order:
// 1) Check if there is an active join - active joins are operated
// against the SOURCE data. The joined data can potentially be
// utilised by any active query or transformIn so we do this step first.
// 2) Check if there is an active query - this is a query that is run
// against the SOURCE data after any active joins have been resolved
// on the source data. This allows an active query to operate on data
// that would only exist after an active join has been executed.
// If the source data does not fall inside the limiting factors of the
// active query then we add it to a removal array. If it does fall
// inside the limiting factors when we add it to an upsert array. This
// is because data that falls inside the query could end up being
// either new data or updated data after a transformIn operation.
// 3) Check if there is a transformIn function. If a transformIn function
// exist we run it against the data after doing any active join and
// active query.
if (hasActiveJoin) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
self._handleChainIO_ActiveJoin(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
}
if (hasActiveQuery) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
self._handleChainIO_ActiveQuery(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
}
if (hasTransformIn) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
self._handleChainIO_TransformIn(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
}
// Check if we still have data to operate on and exit
// if there is none left
if (!sharedData.dataArr.length && !sharedData.removeArr.length) {
// There is no more data to operate on, exit without
// sending any data down the chain reactor (return true
// will tell reactor to exit without continuing)!
return true;
}
// Grab the public data collection's primary key
sharedData.pk = self._data.primaryKey();
// We still have data left, let's work out how to handle it
// first let's loop through the removals as these are easy
if (sharedData.removeArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
self._handleChainIO_RemovePackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
}
if (sharedData.dataArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
self._handleChainIO_UpsertPackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
}
// Now return true to tell the chain reactor not to propagate
// the data itself as we have done all that work here
return true;
};
View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) {
var dataArr = sharedData.dataArr,
removeArr;
// Since we have an active join, all we need to do is operate
// the join clause on each item in the packet's data array.
removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {});
// Now that we've run our join keep in mind that joins can exclude data
// if there is no matching joined data and the require: true clause in
// the join options is enabled. This means we have to store a removal
// array that tells us which items from the original data we sent to
// join did not match the join data and were set with a require flag.
// Now that we have our array of items to remove, let's run through the
// original data and remove them from there.
this.spliceArrayByIndexList(dataArr, removeArr);
// Make sure we add any items we removed to the shared removeArr
sharedData.removeArr = sharedData.removeArr.concat(removeArr);
};
View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
i;
// Now we need to run the data against the active query to
// see if the data should be in the final data list or not,
// so we use the _match method.
// Loop backwards so we can safely splice from the array
// while we are looping
for (i = dataArr.length - 1; i >= 0; i--) {
if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
// The data didn't match the active query, add it
// to the shared removeArr
sharedData.removeArr.push(dataArr[i]);
// Now remove it from the shared dataArr
dataArr.splice(i, 1);
}
}
};
View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
removeArr = sharedData.removeArr,
dataIn = self._data._transformIn,
i;
// At this stage we take the remaining items still left in the data
// array and run our transformIn method on each one, modifying it
// from what it was to what it should be on the view. We also have
// to run this on items we want to remove too because transforms can
// affect primary keys and therefore stop us from identifying the
// correct items to run removal operations on.
// It is important that these are transformed BEFORE they are passed
// to the CRUD methods because we use the CU data to check the position
// of the item in the array and that can only happen if it is already
// pre-transformed. The removal stuff also needs pre-transformed
// because ids can be modified by a transform.
for (i = 0; i < dataArr.length; i++) {
// Assign the new value
dataArr[i] = dataIn(dataArr[i]);
}
for (i = 0; i < removeArr.length; i++) {
// Assign the new value
removeArr[i] = dataIn(removeArr[i]);
}
};
View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) {
var $or = [],
pk = sharedData.pk,
removeArr = sharedData.removeArr,
packet = {
dataSet: removeArr,
query: {
$or: $or
}
},
orObj,
i;
for (i = 0; i < removeArr.length; i++) {
orObj = {};
orObj[pk] = removeArr[i][pk];
$or.push(orObj);
}
ioObj.chainSend('remove', packet);
};
View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) {
var data = this._data,
primaryIndex = data._primaryIndex,
primaryCrc = data._primaryCrc,
pk = sharedData.pk,
dataArr = sharedData.dataArr,
arrItem,
insertArr = [],
updateArr = [],
query,
i;
// Let's work out what type of operation this data should
// generate between an insert or an update.
for (i = 0; i < dataArr.length; i++) {
arrItem = dataArr[i];
// Check if the data already exists in the data
if (primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) {
// The document exists in the data collection but data differs, update required
updateArr.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
insertArr.push(arrItem);
}
}
if (insertArr.length) {
ioObj.chainSend('insert', {
dataSet: insertArr
});
}
if (updateArr.length) {
for (i = 0; i < updateArr.length; i++) {
arrItem = updateArr[i];
query = {};
query[pk] = arrItem[pk];
ioObj.chainSend('update', {
query: query,
update: arrItem,
dataSet: [arrItem]
});
}
}
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this._data.findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this._data.findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._data;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
// Remove the current reference to the _from since we
// are about to replace it with a new one
delete this._from;
}
// Check if we have an existing reactor io that links the
// previous _from source to the view's internal data
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
// Check if we were passed a source name rather than a
// reference to a source object
if (typeof(source) === 'string') {
// We were passed a name, assume it is a collection and
// get the reference to the collection of that name
source = this._db.collection(source);
}
// Check if we were passed a reference to a view rather than
// a collection. Views need to be handled slightly differently
// since their data is stored in an internal data collection
// rather than actually being a direct data source themselves.
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source._data;
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
// Assign the new data source as the view's _from
this._from = source;
// Hook the new data source's drop event so we can unhook
// it as a data source if it gets dropped. This is important
// so that we don't run into problems using a dropped source
// for active data.
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's _from source and determines how they should be interpreted by
// this view. See the _handleChainIO() method which does all the chain packet
// processing for the view.
this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); });
// Set the view's internal data primary key to the same as the
// current active _from data source
this._data.primaryKey(source.primaryKey());
// Do the initial data lookup and populate the view's internal data
// since at this point we don't actually have any data in the view
// yet.
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData, {}, callback);
// If we have an active query and that query has an $orderBy clause,
// update our active bucket which allows us to keep track of where
// data should be placed in our internal data array. This is about
// ordering of data and making sure that we maintain an ordered array
// so that if we have data-binding we can place an item in the data-
// bound view at the correct location. Active buckets use quick-sort
// algorithms to quickly determine the position of an item inside an
// existing array based on a sort protocol.
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type);
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData);
// Rebuild active bucket as well
this.rebuildActiveBucket(this._querySettings.options);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Make sure we are working with an array
if (!(chainPacket.data.dataSet instanceof Array)) {
chainPacket.data.dataSet = [chainPacket.data.dataSet];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._data._insertHandle(arr[index], insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._data._data.length;
this._data._insertHandle(chainPacket.data.dataSet, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"');
}
primaryKey = this._data.primaryKey();
// Do the update
updates = this._data._handleUpdate(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._data._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"');
}
this._data.remove(chainPacket.data.query, chainPacket.options);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the dataSet and remove the objects from the ActiveBucket
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
this._activeBucket.remove(arr[index]);
}
}
break;
default:
break;
}
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._data.ensureIndex.apply(this._data, arguments);
};
/**
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._data.on.apply(this._data, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._data.off.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._data.emit.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._data.deferEmit.apply(this._data, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._data.distinct(key, query, options);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._data.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._data) {
this._data.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._data;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
}
});
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
// TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first!
this.rebuildActiveBucket(options.$orderBy);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
return this;
}
return this._querySettings.options;
};
/**
* Clears the existing active bucket and builds a new one based
* on the passed orderBy object (if one is passed).
* @param {Object=} orderBy The orderBy object describing how to
* order any data.
*/
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._data._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._data.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
var self = this,
refreshResults,
joinArr,
i, k;
if (this._from) {
// Clear the private data collection which will propagate to the public data
// collection automatically via the chain reactor node between them
this._data.remove();
// Grab all the data from the underlying data source
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
// Insert the underlying data into the private data collection
this._data.insert(refreshResults);
// Store the current cursor data
this._data._data.$cursor = refreshResults.$cursor;
this._data._data.$cursor = refreshResults.$cursor;
}
if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Handles when a change has occurred on a collection that is joined
* by query to this view.
* @param objName
* @param objType
* @private
*/
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
// TODO: This is a really dirty solution because it will require a complete
// TODO: rebuild of the view data. We need to implement an IO handler to
// TODO: selectively update the data of the view based on the joined
// TODO: collection data operation.
// FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call
this.refresh();
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._data.count.apply(this._data, arguments);
};
// Call underlying
View.prototype.subset = function () {
return this._data.subset.apply(this._data, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn"
* and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var currentSettings,
newSettings;
currentSettings = this._data.transform();
this._data.transform(obj);
newSettings = this._data.transform();
// Check if transforms are enabled, a dataIn method is set and these
// settings did not match the previous transform settings
if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) {
// The data in the view is now stale, refresh it
this.refresh();
}
return newSettings;
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return this._data.filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.data = function () {
return this._data;
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this._data.indexOf.apply(this._data, arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this._data.db(db);
// Apply the same debug settings
this.debug(db.debug());
this._data.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":5,"./CollectionGroup":6,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (typeof arguments[1] === 'function') {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var hasError = false;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
if (hasError) return;
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
hasError = true;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has nonexistent dependency in ' + requires.join(', '));
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback.apply(null, [null].concat(args));
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
while(!q.paused && workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
var has = Object.prototype.hasOwnProperty;
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (has.call(memo, key)) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (has.call(queues, key)) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":93}],42:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":44}],44:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
var bitsCombined = bits1 | bits2;
words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":44}],46:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":44}],47:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":43,"./core":44}],49:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":44}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":44}],52:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":44}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":43,"./core":44}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":43,"./core":44}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":43,"./core":44}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":43,"./core":44}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":43,"./core":44}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":43,"./core":44}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":43,"./core":44}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":43,"./core":44}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":43,"./core":44}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":43,"./core":44}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":44}],68:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":44}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":44,"./sha256":70}],70:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":44}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":44,"./x64-core":75}],72:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":44,"./x64-core":75}],74:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":44}],76:[function(_dereq_,module,exports){
(function (process,global){
/*!
localForage -- Offline Storage, Improved
Version 1.4.0
https://mozilla.github.io/localForage
(c) 2013-2015 Mozilla, Apache License 2.0
*/
(function() {
var define, requireModule, _dereq_, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = _dereq_ = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("promise/all",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
var isFunction = __dependency1__.isFunction;
/**
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The return promise
is fulfilled with an array that gives all the values in the order they were
passed in the `promises` array argument.
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for RSVP
@param {Array} promises
@param {String} label
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
*/
function all(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve, reject) {
var results = [], remaining = promises.length,
promise;
if (remaining === 0) {
resolve([]);
}
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function resolveAll(index, value) {
results[index] = value;
if (--remaining === 0) {
resolve(results);
}
}
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && isFunction(promise.then)) {
promise.then(resolver(i), reject);
} else {
resolveAll(i, promise);
}
}
});
}
__exports__.all = all;
});
define("promise/asap",
["exports"],
function(__exports__) {
"use strict";
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
// node
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useSetTimeout() {
return function() {
local.setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0], arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
// If length is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush();
}
}
__exports__.asap = asap;
});
define("promise/config",
["exports"],
function(__exports__) {
"use strict";
var config = {
instrument: false
};
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
__exports__.config = config;
__exports__.configure = configure;
});
define("promise/polyfill",
["./promise","./utils","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*global self*/
var RSVPPromise = __dependency1__.Promise;
var isFunction = __dependency2__.isFunction;
function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = RSVPPromise;
}
}
__exports__.polyfill = polyfill;
});
define("promise/promise",
["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) {
"use strict";
var config = __dependency1__.config;
var configure = __dependency1__.configure;
var objectOrFunction = __dependency2__.objectOrFunction;
var isFunction = __dependency2__.isFunction;
var now = __dependency2__.now;
var all = __dependency3__.all;
var race = __dependency4__.race;
var staticResolve = __dependency5__.resolve;
var staticReject = __dependency6__.reject;
var asap = __dependency7__.asap;
var counter = 0;
config.async = asap; // default async is asap;
function Promise(resolver) {
if (!isFunction(resolver)) {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
if (!(this instanceof Promise)) {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
this._subscribers = [];
invokeResolver(resolver, this);
}
function invokeResolver(resolver, promise) {
function resolvePromise(value) {
resolve(promise, value);
}
function rejectPromise(reason) {
reject(promise, reason);
}
try {
resolver(resolvePromise, rejectPromise);
} catch(e) {
rejectPromise(e);
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
try {
value = callback(detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = detail;
succeeded = true;
}
if (handleThenable(promise, value)) {
return;
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
resolve(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
var PENDING = void 0;
var SEALED = 0;
var FULFILLED = 1;
var REJECTED = 2;
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
}
function publish(promise, settled) {
var child, callback, subscribers = promise._subscribers, detail = promise._detail;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
invokeCallback(settled, child, callback, detail);
}
promise._subscribers = null;
}
Promise.prototype = {
constructor: Promise,
_state: undefined,
_detail: undefined,
_subscribers: undefined,
then: function(onFulfillment, onRejection) {
var promise = this;
var thenPromise = new this.constructor(function() {});
if (this._state) {
var callbacks = arguments;
config.async(function invokePromiseCallback() {
invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
});
} else {
subscribe(this, thenPromise, onFulfillment, onRejection);
}
return thenPromise;
},
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
Promise.all = all;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;
function handleThenable(promise, value) {
var then = null,
resolved;
try {
if (promise === value) {
throw new TypeError("A promises callback cannot return that same promise.");
}
if (objectOrFunction(value)) {
then = value.then;
if (isFunction(then)) {
then.call(value, function(val) {
if (resolved) { return true; }
resolved = true;
if (value !== val) {
resolve(promise, val);
} else {
fulfill(promise, val);
}
}, function(val) {
if (resolved) { return true; }
resolved = true;
reject(promise, val);
});
return true;
}
}
} catch (error) {
if (resolved) { return true; }
reject(promise, error);
return true;
}
return false;
}
function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (!handleThenable(promise, value)) {
fulfill(promise, value);
}
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = value;
config.async(publishFulfillment, promise);
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = reason;
config.async(publishRejection, promise);
}
function publishFulfillment(promise) {
publish(promise, promise._state = FULFILLED);
}
function publishRejection(promise) {
publish(promise, promise._state = REJECTED);
}
__exports__.Promise = Promise;
});
define("promise/race",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
/**
`RSVP.race` allows you to watch a series of promises and act as soon as the
first promise given to the `promises` argument fulfills or rejects.
Example:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 2");
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// result === "promise 2" because it was resolved before promise1
// was resolved.
});
```
`RSVP.race` is deterministic in that only the state of the first completed
promise matters. For example, even if other promises given to the `promises`
array argument are resolved, but the first completed promise has become
rejected before the other promises became fulfilled, the returned promise
will become rejected:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error("promise 2"));
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// Code here never runs because there are rejected promises!
}, function(reason){
// reason.message === "promise2" because promise 2 became rejected before
// promise 1 became fulfilled
});
```
@method race
@for RSVP
@param {Array} promises array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise that becomes fulfilled with the value the first
completed promises is resolved with if the first completed promise was
fulfilled, or rejected with the reason that the first completed promise
was rejected with.
*/
function race(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve, reject) {
var results = [], promise;
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
});
}
__exports__.race = race;
});
define("promise/reject",
["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.reject` returns a promise that will become rejected with the passed
`reason`. `RSVP.reject` is essentially shorthand for the following:
```javascript
var promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = RSVP.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@for RSVP
@param {Any} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become rejected with the given
`reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Promise = this;
return new Promise(function (resolve, reject) {
reject(reason);
});
}
__exports__.reject = reject;
});
define("promise/resolve",
["exports"],
function(__exports__) {
"use strict";
function resolve(value) {
/*jshint validthis:true */
if (value && typeof value === 'object' && value.constructor === this) {
return value;
}
var Promise = this;
return new Promise(function(resolve) {
resolve(value);
});
}
__exports__.resolve = resolve;
});
define("promise/utils",
["exports"],
function(__exports__) {
"use strict";
function objectOrFunction(x) {
return isFunction(x) || (typeof x === "object" && x !== null);
}
function isFunction(x) {
return typeof x === "function";
}
function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
// Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now || function() { return new Date().getTime(); };
__exports__.objectOrFunction = objectOrFunction;
__exports__.isFunction = isFunction;
__exports__.isArray = isArray;
__exports__.now = now;
});
requireModule('promise/polyfill').polyfill();
}());(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["localforage"] = factory();
else
root["localforage"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var localForage = (function (globalObject) {
'use strict';
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'];
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
var driverSupport = (function (self) {
var result = {};
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
result[DriverType.INDEXEDDB] = !!(function () {
try {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB;
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) {
return false;
}
return indexedDB && typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.WEBSQL] = !!(function () {
try {
return self.openDatabase;
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function () {
try {
return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem;
} catch (e) {
return false;
}
})();
return result;
})(globalObject);
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var LocalForage = (function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
this.INDEXEDDB = DriverType.INDEXEDDB;
this.LOCALSTORAGE = DriverType.LOCALSTORAGE;
this.WEBSQL = DriverType.WEBSQL;
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver);
}
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof options === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
var namingError = new Error('Custom driver name already in use: ' + driverObject._driver);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function (supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
promise.then(callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var self = this;
var getDriverPromise = (function () {
if (isLibraryDriver(driverName)) {
switch (driverName) {
case self.INDEXEDDB:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(1));
});
case self.LOCALSTORAGE:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(2));
});
case self.WEBSQL:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(4));
});
}
} else if (CustomDrivers[driverName]) {
return Promise.resolve(CustomDrivers[driverName]);
}
return Promise.reject(new Error('Driver not found.'));
})();
getDriverPromise.then(callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
});
if (callback && typeof callback === 'function') {
serializerPromise.then(function (result) {
callback(result);
});
}
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
promise.then(callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
})['catch'](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () {
return Promise.resolve();
}) : Promise.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})['catch'](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
});
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
})();
return new LocalForage();
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localForage;
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
'use strict';
exports.__esModule = true;
var asyncStorage = (function (globalObject) {
'use strict';
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || globalObject.indexedDB || globalObject.webkitIndexedDB || globalObject.mozIndexedDB || globalObject.OIndexedDB || globalObject.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
var dbContexts;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({ status: xhr.status, response: xhr.response });
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function (resolve, reject) {
var blob = _createBlob([''], { type: 'image/png' });
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function () {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function (e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function (res) {
resolve(!!(res && res.type === 'image/png'));
}, function () {
resolve(false);
}).then(function () {
URL.revokeObjectURL(url);
});
};
};
txn.onerror = txn.onabort = reject;
})['catch'](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Specialize the default `ready()` function by making it dependent
// on the current database operations. Thus, the driver will be actually
// ready when it's been initialized (default) *and* there are no pending
// operations on the database (initiated by some other instances).
function _fullyReady(callback) {
var self = this;
var promise = self._initReady().then(function () {
var dbContext = dbContexts[self._dbInfo.name];
if (dbContext && dbContext.dbReady) {
return dbContext.dbReady;
}
});
promise.then(callback, callback);
return promise;
}
function _deferReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Create a deferred object representing the current database operation.
var deferredOperation = {};
deferredOperation.promise = new Promise(function (resolve) {
deferredOperation.resolve = resolve;
});
// Enqueue the deferred operation.
dbContext.deferredOperations.push(deferredOperation);
// Chain its promise to the database readiness.
if (!dbContext.dbReady) {
dbContext.dbReady = deferredOperation.promise;
} else {
dbContext.dbReady = dbContext.dbReady.then(function () {
return deferredOperation.promise;
});
}
}
function _advanceReadiness(dbInfo) {
var dbContext = dbContexts[dbInfo.name];
// Dequeue a deferred operation.
var deferredOperation = dbContext.deferredOperations.pop();
// Resolve its promise (which is part of the database readiness
// chain of promises).
if (deferredOperation) {
deferredOperation.resolve();
}
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Initialize a singleton container for all running localForages.
if (!dbContexts) {
dbContexts = {};
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null,
// Database readiness (promise).
dbReady: null,
// Deferred operations on the database.
deferredOperations: []
};
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(self);
// Replace the default `ready()` function with the specialized one.
if (!self._initReady) {
self._initReady = self.ready;
self.ready = _fullyReady;
}
// Create an array of initialization states of the related localForages.
var initPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== self) {
// Don't wait for itself...
initPromises.push(forage._initReady()['catch'](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise.all(initPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k = 0; k < forages.length; k++) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise(function (resolve, reject) {
if (dbInfo.db) {
if (upgradeNeeded) {
_deferReadiness(dbInfo);
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = indexedDB.open.apply(indexedDB, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function () {
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
_advanceReadiness(dbInfo);
};
});
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void 0) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
if (value instanceof Blob) {
return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
if (blobSupport) {
return value;
}
return _encodeBlob(value);
});
}
return value;
}).then(function (value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
var req = store.put(value, key);
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
return asyncStorage;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = asyncStorage;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
'use strict';
exports.__esModule = true;
var localStorageWrapper = (function (globalObject) {
'use strict';
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!globalObject.localStorage || !('setItem' in globalObject.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = globalObject.localStorage;
} catch (e) {
return;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
if (dbInfo.storeName !== self._defaultConfig.storeName) {
dbInfo.keyPrefix += dbInfo.storeName + '/';
}
self._dbInfo = dbInfo;
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
return localStorageWrapper;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localStorageWrapper;
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var localforageSerializer = (function (globalObject) {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
return localforageSerializer;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = localforageSerializer;
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
'use strict';
exports.__esModule = true;
var webSQLStorage = (function (globalObject) {
'use strict';
var openDatabase = globalObject.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return reject(e);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
});
});
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
return webSQLStorage;
})(typeof window !== 'undefined' ? window : self);
exports['default'] = webSQLStorage;
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":93}],77:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":78,"./lib/inflate":79,"./lib/utils/common":80,"./lib/zlib/constants":83}],78:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var ZStream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
function Deflate(options) {
if (!(this instanceof Deflate)) return new Deflate(options);
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new ZStream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
}
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function (data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function (status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate algorithm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":80,"./utils/strings":81,"./zlib/deflate":85,"./zlib/messages":90,"./zlib/zstream":92}],79:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var ZStream = _dereq_('./zlib/zstream');
var GZheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
function Inflate(options) {
if (!(this instanceof Inflate)) return new Inflate(options);
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new ZStream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new GZheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
}
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function (data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function (chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function (status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":80,"./utils/strings":81,"./zlib/constants":83,"./zlib/gzheader":86,"./zlib/inflate":88,"./zlib/messages":90,"./zlib/zstream":92}],80:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function (chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i = 0, l = chunks.length; i < l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i = 0, l = chunks.length; i < l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i = 0; i < len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function (chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],81:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q = 0; q < 256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
c2 = str.charCodeAt(m_pos + 1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i = 0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function (buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function (str) {
var buf = new utils.Buf8(str.length);
for (var i = 0, len = buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len * 2);
for (out = 0, i = 0; i < len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function (buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max - 1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":80}],82:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],83:[function(_dereq_,module,exports){
'use strict';
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],84:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n = 0; n < 256; n++) {
c = n;
for (var k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc ^= -1;
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],85:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only(s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH - 1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH - 1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length - 1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH - 1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
function Config(good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS + 1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":80,"./adler32":82,"./crc32":84,"./messages":90,"./trees":91}],86:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],87:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],88:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function zswap32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window, src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window, src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = zswap32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = { bits: state.lenbits };
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = { bits: state.lenbits };
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = { bits: state.distbits };
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
if ((state.flags ? hold : zswap32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":80,"./adler32":82,"./crc32":84,"./inffast":87,"./inftrees":89}],89:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i = 0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":80}],90:[function(_dereq_,module,exports){
'use strict';
module.exports = {
2: 'need dictionary', /* Z_NEED_DICT 2 */
1: 'stream end', /* Z_STREAM_END 1 */
0: '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],91:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2 * L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
/* eslint-disable comma-spacing,array-bracket-spacing */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* eslint-enable comma-spacing,array-bracket-spacing */
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES + 2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
}
var static_l_desc;
var static_d_desc;
var static_bl_desc;
function TreeDesc(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
}
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short(s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n * 2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n - base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length - 1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m * 2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
tree[m * 2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n * 2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS + 1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES - 1; code++) {
base_length[code] = length;
for (n = 0; n < (1 << extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length - 1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1 << extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n * 2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n * 2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n * 2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n * 2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES + 1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n * 2 + 1]/*.Len*/ = 5;
static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n * 2;
var _m2 = m * 2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code + LITERALS + 1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n * 2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node * 2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count - 3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count - 3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes - 1, 5);
send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES << 1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len + 3 + 7) >>> 3;
static_lenb = (s.static_len + 3 + 7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc * 2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize - 1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":80}],92:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}],93:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}]},{},[1]);
| x112358/cdnjs | ajax/libs/forerunnerdb/1.3.737/fdb-legacy.js | JavaScript | mit | 996,478 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class AsyncTaskMethodBuilderTests
{
// Test captured sync context with successful completion (SetResult)
[Fact]
public static void VoidMethodBuilder_TrackedContext()
{
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
// TrackedCount should increase as Create() is called, and decrease as SetResult() is called.
// Completing in opposite order as created.
var avmb1 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
var avmb2 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb2.SetResult();
Assert.Equal(1, trackedContext.TrackedCount);
avmb1.SetResult();
Assert.Equal(0, trackedContext.TrackedCount);
// Completing in same order as created
avmb1 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
avmb2 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb1.SetResult();
Assert.Equal(1, trackedContext.TrackedCount);
avmb2.SetResult();
Assert.Equal(0, trackedContext.TrackedCount);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Test not having a sync context with successful completion (SetResult)
[Fact]
public static void VoidMethodBuilder_NoContext()
{
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
// Make sure not having a sync context doesn't cause us to blow up
SynchronizationContext.SetSynchronizationContext(null);
var avmb = AsyncVoidMethodBuilder.Create();
avmb.SetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// AsyncTaskMethodBuilder
[Fact]
public static void TaskMethodBuilder_Basic()
{
// Creating a task builder, building it, completing it successfully
{
var atmb = AsyncTaskMethodBuilder.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetResult();
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
}
}
[Fact]
public static void TaskMethodBuilder_DoesNotTouchSyncContext()
{
// Verify that AsyncTaskMethodBuilder is not touching sync context
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
var atmb = AsyncTaskMethodBuilder.Create();
Assert.Equal(0, trackedContext.TrackedCount);
atmb.SetResult();
Assert.Equal(0, trackedContext.TrackedCount);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// AsyncTaskMethodBuilder<T>
[Fact]
public static void TaskMethodBuilderT_Basic()
{
// Creating a task builder, building it, completing it successfully
var atmb = AsyncTaskMethodBuilder<int>.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetResult(43);
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
Assert.Equal(43, t.Result);
}
[Fact]
public static void TaskMethodBuilderT_DoesNotTouchSyncContext()
{
// Verify that AsyncTaskMethodBuilder<T> is not touching sync context
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
var atmb = AsyncTaskMethodBuilder<string>.Create();
Assert.Equal(0, trackedContext.TrackedCount);
atmb.SetResult("async");
Assert.Equal(0, trackedContext.TrackedCount);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Incorrect usage for AsyncTaskMethodBuilder
[Fact]
public static void TaskMethodBuilder_IncorrectUsage()
{
var atmb = new AsyncTaskMethodBuilder();
Assert.Throws<ArgumentNullException>(() => { atmb.SetException(null); });
}
// Incorrect usage for AsyncVoidMethodBuilder
[Fact]
public static void VoidMethodBuilder_IncorrectUsage()
{
var avmb = AsyncVoidMethodBuilder.Create();
Assert.Throws<ArgumentNullException>(() => { avmb.SetException(null); });
avmb.SetResult();
}
// Creating a task builder, building it, completing it successfully, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilder_CantBeReset()
{
var atmb = AsyncTaskMethodBuilder.Create();
atmb.SetResult();
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Incorrect usage for AsyncTaskMethodBuilder<T>
[Fact]
public static void TaskMethodBuilderT_IncorrectUsage()
{
var atmb = new AsyncTaskMethodBuilder<int>();
Assert.Throws<ArgumentNullException>(() => { atmb.SetException(null); });
}
// Creating a task builder <T>, building it, completing it successfully, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilderT_CantBeReset()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
atmb.SetResult(43);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Creating a task builder, building it, completing it faulted, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilder_SetException_CantBeReset0()
{
var atmb = AsyncTaskMethodBuilder.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetException(new InvalidCastException());
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.True(t.Exception.InnerException is InvalidCastException, "Wrong exception found in builder (ATMB, build then fault)");
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Creating a task builder, completing it faulted, building it, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilder_SetException_CantBeReset1()
{
var atmb = AsyncTaskMethodBuilder.Create();
atmb.SetException(new InvalidCastException());
var t = atmb.Task;
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.True(t.Exception.InnerException is InvalidCastException, "Wrong exception found in builder (ATMB, fault then build)");
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Test cancellation
[Fact]
public static void TaskMethodBuilder_Cancellation()
{
var atmb = AsyncTaskMethodBuilder.Create();
var oce = new OperationCanceledException();
atmb.SetException(oce);
var t = atmb.Task;
Assert.Equal(TaskStatus.Canceled, t.Status);
OperationCanceledException caught = Assert.Throws<OperationCanceledException>(() =>
{
t.GetAwaiter().GetResult();
});
Assert.Same(oce, caught);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
[Fact]
public static void AsyncMethodBuilderCreate_SetExceptionTest2()
{
// Test captured sync context with exceptional completion
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var trackedContext = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(trackedContext);
// Completing in opposite order as created
var avmb1 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
var avmb2 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb2.SetException(new InvalidOperationException("uh oh 1"));
Assert.Equal(1, trackedContext.TrackedCount);
avmb1.SetException(new InvalidCastException("uh oh 2"));
Assert.Equal(0, trackedContext.TrackedCount);
Assert.Equal(2, trackedContext.PostExceptions.Count);
Assert.IsType<InvalidOperationException>(trackedContext.PostExceptions[0]);
Assert.IsType<InvalidCastException>(trackedContext.PostExceptions[1]);
// Completing in same order as created
var avmb3 = AsyncVoidMethodBuilder.Create();
Assert.Equal(1, trackedContext.TrackedCount);
var avmb4 = AsyncVoidMethodBuilder.Create();
Assert.Equal(2, trackedContext.TrackedCount);
avmb3.SetException(new InvalidOperationException("uh oh 3"));
Assert.Equal(1, trackedContext.TrackedCount);
avmb4.SetException(new InvalidCastException("uh oh 4"));
Assert.Equal(0, trackedContext.TrackedCount);
Assert.Equal(4, trackedContext.PostExceptions.Count);
Assert.IsType<InvalidOperationException>(trackedContext.PostExceptions[2]);
Assert.IsType<InvalidCastException>(trackedContext.PostExceptions[3]);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Creating a task builder, building it, completing it faulted, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilderT_SetExceptionTest0()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
var t = atmb.Task;
Assert.Equal(TaskStatus.WaitingForActivation, t.Status);
atmb.SetException(new InvalidCastException());
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.IsType<InvalidCastException>(t.Exception.InnerException);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Creating a task builder, completing it faulted, building it, and making sure it can't be reset
[Fact]
public static void TaskMethodBuilderT_SetExceptionTest1()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
atmb.SetException(new InvalidCastException());
var t = atmb.Task;
Assert.Equal(TaskStatus.Faulted, t.Status);
Assert.IsType<InvalidCastException>(t.Exception.InnerException);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
// Test cancellation
[Fact]
public static void TaskMethodBuilderT_Cancellation()
{
var atmb = AsyncTaskMethodBuilder<int>.Create();
var oce = new OperationCanceledException();
atmb.SetException(oce);
var t = atmb.Task;
Assert.Equal(TaskStatus.Canceled, t.Status);
OperationCanceledException e = Assert.Throws<OperationCanceledException>(() =>
{
t.GetAwaiter().GetResult();
});
Assert.Same(oce, e);
Assert.Throws<InvalidOperationException>(() => { atmb.SetResult(44); });
Assert.Throws<InvalidOperationException>(() => { atmb.SetException(new Exception()); });
}
[Fact]
public static void TaskMethodBuilder_TaskIsCached()
{
var atmb = new AsyncTaskMethodBuilder();
var t1 = atmb.Task;
var t2 = atmb.Task;
Assert.NotNull(t1);
Assert.NotNull(t2);
Assert.Same(t1, t2);
}
[Fact]
public static void TaskMethodBuilderT_TaskIsCached()
{
var atmb = new AsyncTaskMethodBuilder<int>();
var t1 = atmb.Task;
var t2 = atmb.Task;
Assert.NotNull(t1);
Assert.NotNull(t2);
Assert.Same(t1, t2);
}
[Fact]
public static void TaskMethodBuilder_UsesCompletedCache()
{
var atmb1 = new AsyncTaskMethodBuilder();
var atmb2 = new AsyncTaskMethodBuilder();
atmb1.SetResult();
atmb2.SetResult();
Assert.Same(atmb1.Task, atmb2.Task);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void TaskMethodBuilderBoolean_UsesCompletedCache(bool result)
{
TaskMethodBuilderT_UsesCompletedCache(result, true);
}
[Theory]
[InlineData(0, true)]
[InlineData(5, true)]
[InlineData(-5, false)]
[InlineData(42, false)]
public static void TaskMethodBuilderInt32_UsesCompletedCache(int result, bool shouldBeCached)
{
TaskMethodBuilderT_UsesCompletedCache(result, shouldBeCached);
}
[Theory]
[InlineData((string)null, true)]
[InlineData("test", false)]
public static void TaskMethodBuilderRef_UsesCompletedCache(string result, bool shouldBeCached)
{
TaskMethodBuilderT_UsesCompletedCache(result, shouldBeCached);
}
private static void TaskMethodBuilderT_UsesCompletedCache<T>(T result, bool shouldBeCached)
{
var atmb1 = new AsyncTaskMethodBuilder<T>();
var atmb2 = new AsyncTaskMethodBuilder<T>();
atmb1.SetResult(result);
atmb2.SetResult(result);
Assert.Equal(shouldBeCached, object.ReferenceEquals(atmb1.Task, atmb2.Task));
}
[Fact]
public static void Tcs_ValidateFaultedTask()
{
var tcs = new TaskCompletionSource<int>();
try { throw new InvalidOperationException(); }
catch (Exception e) { tcs.SetException(e); }
ValidateFaultedTask(tcs.Task);
}
[Fact]
public static void TaskMethodBuilder_ValidateFaultedTask()
{
var atmb = AsyncTaskMethodBuilder.Create();
try { throw new InvalidOperationException(); }
catch (Exception e) { atmb.SetException(e); }
ValidateFaultedTask(atmb.Task);
}
[Fact]
public static void TaskMethodBuilderT_ValidateFaultedTask()
{
var atmbtr = AsyncTaskMethodBuilder<object>.Create();
try { throw new InvalidOperationException(); }
catch (Exception e) { atmbtr.SetException(e); }
ValidateFaultedTask(atmbtr.Task);
}
[Fact]
public static void TrackedSyncContext_ValidateException()
{
SynchronizationContext previousContext = SynchronizationContext.Current;
try
{
var tosc = new TrackOperationsSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(tosc);
var avmb = AsyncVoidMethodBuilder.Create();
try { throw new InvalidOperationException(); }
catch (Exception exc) { avmb.SetException(exc); }
Assert.NotEmpty(tosc.PostExceptions);
ValidateException(tosc.PostExceptions[0]);
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
// Running tasks with exceptions.
[Fact]
public static void FaultedTaskExceptions()
{
var twa1 = Task.Run(() => { throw new Exception("uh oh"); });
var twa2 = Task.Factory.StartNew(() => { throw new Exception("uh oh"); });
var tasks = new Task[]
{
Task.Run(() => { throw new Exception("uh oh"); }),
Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); }),
Task.WhenAll(Task.Run(() => { throw new Exception("uh oh"); }), Task.Run(() => { throw new Exception("uh oh"); })),
Task.WhenAll<int>(Task.Run(new Func<int>(() => { throw new Exception("uh oh"); })), Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))),
Task.WhenAny(twa1, twa2).Unwrap(),
Task.WhenAny<int>(Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); }))).Unwrap(),
Task.Factory.StartNew(() => Task.Factory.StartNew(() => { throw new Exception("uh oh"); })).Unwrap(),
Task.Factory.StartNew<Task<int>>(() => Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); })).Unwrap(),
Task.Run(() => Task.Run(() => { throw new Exception("uh oh"); })),
Task.Run(() => Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))),
Task.Run(new Func<Task>(() => { throw new Exception("uh oh"); })),
Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); }))
};
for (int i = 0; i < tasks.Length; i++)
{
ValidateFaultedTask(tasks[i]);
}
((IAsyncResult)twa1).AsyncWaitHandle.WaitOne();
((IAsyncResult)twa2).AsyncWaitHandle.WaitOne();
Exception ignored = twa1.Exception;
ignored = twa2.Exception;
}
// Test that OCEs don't result in the unobserved event firing
[Fact]
public static void CancellationDoesntResultInEventFiring()
{
var cts = new CancellationTokenSource();
var oce = new OperationCanceledException(cts.Token);
// A Task that throws an exception to cancel
var b = new Barrier(2);
Task t1 = Task.Factory.StartNew(() =>
{
b.SignalAndWait();
b.SignalAndWait();
throw oce;
}, cts.Token);
b.SignalAndWait(); // make sure task is started before we cancel
cts.Cancel();
b.SignalAndWait(); // release task to complete
// This test may be run concurrently with other tests in the suite,
// which can be problematic as TaskScheduler.UnobservedTaskException
// is global state. The handler is carefully written to be non-problematic
// if it happens to be set during the execution of another test that has
// an unobserved exception.
EventHandler<UnobservedTaskExceptionEventArgs> handler =
(s, e) => Assert.DoesNotContain(oce, e.Exception.InnerExceptions);
TaskScheduler.UnobservedTaskException += handler;
((IAsyncResult)t1).AsyncWaitHandle.WaitOne();
t1 = null;
for (int i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
TaskScheduler.UnobservedTaskException -= handler;
}
#region Helper Methods / Classes
private static void ValidateFaultedTask(Task t)
{
((IAsyncResult)t).AsyncWaitHandle.WaitOne();
Assert.True(t.IsFaulted);
Exception e = Assert.ThrowsAny<Exception>(() =>
{
t.GetAwaiter().GetResult();
});
ValidateException(e);
}
private static void ValidateException(Exception e)
{
Assert.NotNull(e);
Assert.NotNull(e.StackTrace);
Assert.Contains("End of stack trace", e.StackTrace);
}
private class TrackOperationsSynchronizationContext : SynchronizationContext
{
private int _trackedCount;
private int _postCount;
//ConcurrentQueue
private List<Exception> _postExceptions = new List<Exception>();
public int TrackedCount { get { return _trackedCount; } }
public List<Exception> PostExceptions
{
get
{
List<Exception> returnValue;
lock (_postExceptions)
{
returnValue = new List<Exception>(_postExceptions);
return returnValue;
}
}
}
public int PostCount { get { return _postCount; } }
public override void OperationStarted() { Interlocked.Increment(ref _trackedCount); }
public override void OperationCompleted() { Interlocked.Decrement(ref _trackedCount); }
public override void Post(SendOrPostCallback callback, object state)
{
try
{
Interlocked.Increment(ref _postCount);
callback(state);
}
catch (Exception exc)
{
lock (_postExceptions)
{
_postExceptions.Add(exc);
}
}
}
}
#endregion
}
}
| Petermarcu/corefx | src/System.Threading.Tasks/tests/System.Runtime.CompilerServices/AsyncTaskMethodBuilderTests.cs | C# | mit | 23,786 |
/*! elasticsearch - v11.0.0 - 2016-04-05
* http://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
* Copyright (c) 2016 Elasticsearch BV; Licensed Apache-2.0 */
;(function () {
/* prevent lodash from detecting external amd loaders */var define;
!function(a){"object"==typeof exports?module.g=a():"function"==typeof define&&define.amd?define(a):"undefined"!=typeof window?window.h=a():"undefined"!=typeof global?global.h=a():"undefined"!=typeof self&&(self.h=a())}(function(){var a;return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw Error("Cannot find module '"+g+"'")}var j=c[g]={g:{}};b[g][0].call(j.g,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.g,a,b,c,d)}return c[g].g}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b){function c(a){i.length||(e(),j=!0),i[i.length]=a}function d(){for(;k<i.length;){var a=k;if(k+=1,i[a].call(),k>l){for(var b=0,c=i.length-k;c>b;b++)i[b]=i[b+k];i.length-=k,k=0}}i.length=0,k=0,j=!1}function e(){var b=g.domain;b&&(f||(f=a("domain")),f.active=g.domain=null),j&&h?setImmediate(d):g.i(d),b&&(f.active=g.domain=b)}var f,g=a("__browserify_process"),h="function"==typeof setImmediate;b.g=c;var i=[],j=!1,k=0,l=1024;c.j=e},{k:16,domain:5}],2:[function(a,b,c){var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(a){"use strict";function b(a){var b=a.charCodeAt(0);return b===g||b===l?62:b===h||b===m?63:i>b?-1:i+10>b?b-i+26+26:k+26>b?b-k:j+26>b?b-j+26:void 0}function c(a){function c(a){j[l++]=a}var d,e,g,h,i,j;if(a.length%4>0)throw Error("Invalid string. Length must be a multiple of 4");var k=a.length;i="="===a.charAt(k-2)?2:"="===a.charAt(k-1)?1:0,j=new f(3*a.length/4-i),g=i>0?a.length-4:a.length;var l=0;for(d=0,e=0;g>d;d+=4,e+=3)h=b(a.charAt(d))<<18|b(a.charAt(d+1))<<12|b(a.charAt(d+2))<<6|b(a.charAt(d+3)),c((16711680&h)>>16),c((65280&h)>>8),c(255&h);return 2===i?(h=b(a.charAt(d))<<2|b(a.charAt(d+1))>>4,c(255&h)):1===i&&(h=b(a.charAt(d))<<10|b(a.charAt(d+1))<<4|b(a.charAt(d+2))>>2,c(h>>8&255),c(255&h)),j}function e(a){function b(a){return d.charAt(a)}function c(a){return b(a>>18&63)+b(a>>12&63)+b(a>>6&63)+b(63&a)}var e,f,g,h=a.length%3,i="";for(e=0,g=a.length-h;g>e;e+=3)f=(a[e]<<16)+(a[e+1]<<8)+a[e+2],i+=c(f);switch(h){case 1:f=a[a.length-1],i+=b(f>>2),i+=b(f<<4&63),i+="==";break;case 2:f=(a[a.length-2]<<8)+a[a.length-1],i+=b(f>>10),i+=b(f>>4&63),i+=b(f<<2&63),i+="="}return i}var f="undefined"!=typeof Uint8Array?Uint8Array:Array,g="+".charCodeAt(0),h="/".charCodeAt(0),i="0".charCodeAt(0),j="a".charCodeAt(0),k="A".charCodeAt(0),l="-".charCodeAt(0),m="_".charCodeAt(0);a.l=c,a.m=e}(void 0===c?this.o={}:c)},{}],3:[function(a,b,c){function d(a){return"[object Array]"===j.call(a)}function e(a,b){var c;if(null===a)c={__proto__:null};else{if("object"!=typeof a)throw new TypeError("typeof prototype["+typeof a+"] != 'object'");var d=function(){};d.prototype=a,c=new d,c.__proto__=a}return void 0!==b&&Object.defineProperties&&Object.defineProperties(c,b),c}function f(a){return"object"!=typeof a&&"function"!=typeof a||null===a}function g(a){if(f(a))throw new TypeError("Object.keys called on a non-object");var b=[];for(var c in a)k.call(a,c)&&b.push(c);return b}function h(a){if(f(a))throw new TypeError("Object.getOwnPropertyNames called on a non-object");var b=g(a);return c.isArray(a)&&-1===c.indexOf(a,"length")&&b.push("length"),b}function i(a,b){return{value:a[b]}}var j=Object.prototype.toString,k=Object.prototype.hasOwnProperty;c.isArray="function"==typeof Array.isArray?Array.isArray:d,c.indexOf=function(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c<a.length;c++)if(b===a[c])return c;return-1},c.filter=function(a,b){if(a.filter)return a.filter(b);for(var c=[],d=0;d<a.length;d++)b(a[d],d,a)&&c.push(a[d]);return c},c.forEach=function(a,b,c){if(a.forEach)return a.forEach(b,c);for(var d=0;d<a.length;d++)b.call(c,a[d],d,a)},c.map=function(a,b){if(a.map)return a.map(b);for(var c=Array(a.length),d=0;d<a.length;d++)c[d]=b(a[d],d,a);return c},c.reduce=function(a,b,c){if(a.reduce)return a.reduce(b,c);var d,e=!1;2<arguments.length&&(d=c,e=!0);for(var f=0,g=a.length;g>f;++f)a.hasOwnProperty(f)&&(e?d=b(d,a[f],f,a):(d=a[f],e=!0));return d},"b"!=="ab".substr(-1)?c.substr=function(a,b,c){return 0>b&&(b=a.length+b),a.substr(b,c)}:c.substr=function(a,b,c){return a.substr(b,c)},c.trim=function(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")},c.bind=function(){var a=Array.prototype.slice.call(arguments),b=a.shift();if(b.bind)return b.bind.apply(b,a);var c=a.shift();return function(){b.apply(c,a.concat([Array.prototype.slice.call(arguments)]))}},c.create="function"==typeof Object.create?Object.create:e;var l="function"==typeof Object.keys?Object.keys:g,m="function"==typeof Object.getOwnPropertyNames?Object.getOwnPropertyNames:h;if(Error().hasOwnProperty("description")){var n=function(a,b){return"[object Error]"===j.call(a)&&(b=c.filter(b,function(a){return"description"!==a&&"number"!==a&&"message"!==a})),b};c.keys=function(a){return n(a,l(a))},c.getOwnPropertyNames=function(a){return n(a,m(a))}}else c.keys=l,c.getOwnPropertyNames=m;if("function"==typeof Object.getOwnPropertyDescriptor)try{Object.getOwnPropertyDescriptor({a:1},"a"),c.getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor}catch(a){c.getOwnPropertyDescriptor=function(a,b){try{return Object.getOwnPropertyDescriptor(a,b)}catch(c){return i(a,b)}}}else c.getOwnPropertyDescriptor=i},{}],4:[function(a,b){function c(a,b){return m.p(b)?""+b:!m.q(b)||!isNaN(b)&&isFinite(b)?m.s(b)||m.t(b)?""+b:b:""+b}function d(a,b){return m.u(a)?a.length<b?a:a.slice(0,b):a}function e(a){return d(JSON.stringify(a.v,c),128)+" "+a.operator+" "+d(JSON.stringify(a.A,c),128)}function f(a,b,c,d,e){throw new p.B({message:c,v:a,A:b,operator:d,C:e})}function g(a,b){a||f(a,!0,b,"==",p.ok)}function h(a,b){if(a===b)return!0;if(m.isBuffer(a)&&m.isBuffer(b)){if(a.length!=b.length)return!1;for(var c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}return m.D(a)&&m.D(b)?a.getTime()===b.getTime():m.t(a)&&m.t(b)?a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.lastIndex===b.lastIndex&&a.ignoreCase===b.ignoreCase:m.F(a)||m.F(b)?j(a,b):a==b}function i(a){return"[object Arguments]"==Object.prototype.toString.call(a)}function j(a,b){if(m.G(a)||m.G(b))return!1;if(a.prototype!==b.prototype)return!1;if(i(a))return i(b)?(a=o.call(a),b=o.call(b),h(a,b)):!1;try{var c,d,e=n.keys(a),f=n.keys(b)}catch(a){return!1}if(e.length!=f.length)return!1;for(e.sort(),f.sort(),d=e.length-1;d>=0;d--)if(e[d]!=f[d])return!1;for(d=e.length-1;d>=0;d--)if(c=e[d],!h(a[c],b[c]))return!1;return!0}function k(a,b){return a&&b?"[object RegExp]"==Object.prototype.toString.call(b)?b.test(a):a instanceof b?!0:b.call({},a)===!0:!1}function l(a,b,c,d){var e;m.u(c)&&(d=c,c=null);try{b()}catch(a){e=a}if(d=(c&&c.name?" ("+c.name+").":".")+(d?" "+d:"."),a&&!e&&f(e,c,"Missing expected exception"+d),!a&&k(e,c)&&f(e,c,"Got unwanted exception"+d),a&&e&&c&&!k(e,c)||!a&&e)throw e}var m=a("util"),n=a("_shims"),o=Array.prototype.slice,p=b.g=g;p.B=function(a){this.name="AssertionError",this.v=a.v,this.A=a.A,this.operator=a.operator,this.message=a.message||e(this)},m.H(p.B,Error),p.I=f,p.ok=g,p.J=function(a,b,c){a!=b&&f(a,b,c,"==",p.J)},p.K=function(a,b,c){a==b&&f(a,b,c,"!=",p.K)},p.L=function(a,b,c){h(a,b)||f(a,b,c,"deepEqual",p.L)},p.M=function(a,b,c){h(a,b)&&f(a,b,c,"notDeepEqual",p.M)},p.N=function(a,b,c){a!==b&&f(a,b,c,"===",p.N)},p.O=function(a,b,c){a===b&&f(a,b,c,"!==",p.O)},p.P=function(){l.apply(this,[!0].concat(o.call(arguments)))},p.R=function(){l.apply(this,[!1].concat(o.call(arguments)))},p.S=function(a){if(a)throw a}},{T:3,U:10}],5:[function(){},{}],6:[function(a,b){function c(){this.V=this.V||{},this.W=this.W||void 0}var d=a("util");b.g=c,c.X=c,c.prototype.V=void 0,c.prototype.W=void 0,c.Y=10,c.prototype.Z=function(a){if(!d.q(a)||0>a)throw TypeError("n must be a positive number");return this.W=a,this},c.prototype.$=function(a){var b,c,e,f,g,h;if(this.V||(this.V={}),"error"===a&&(!this.V.error||d.F(this.V.error)&&!this.V.error.length))throw b=arguments[1],b instanceof Error?b:TypeError('Uncaught, unspecified "error" event.');if(c=this.V[a],d.p(c))return!1;if(d.s(c))switch(arguments.length){case 1:c.call(this);break;case 2:c.call(this,arguments[1]);break;case 3:c.call(this,arguments[1],arguments[2]);break;default:for(e=arguments.length,f=Array(e-1),g=1;e>g;g++)f[g-1]=arguments[g];c.apply(this,f)}else if(d.F(c)){for(e=arguments.length,f=Array(e-1),g=1;e>g;g++)f[g-1]=arguments[g];for(h=c.slice(),e=h.length,g=0;e>g;g++)h[g].apply(this,f)}return!0},c.prototype.addListener=function(a,b){var e;if(!d.s(b))throw TypeError("listener must be a function");if(this.V||(this.V={}),this.V.newListener&&this.$("newListener",a,d.s(b.listener)?b.listener:b),this.V[a]?d.F(this.V[a])?this.V[a].push(b):this.V[a]=[this.V[a],b]:this.V[a]=b,d.F(this.V[a])&&!this.V[a]._){var e;e=d.p(this.W)?c.Y:this.W,e&&e>0&&this.V[a].length>e&&(this.V[a]._=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this.V[a].length),console.trace())}return this},c.prototype.aa=c.prototype.addListener,c.prototype.ba=function(a,b){function c(){this.removeListener(a,c),b.apply(this,arguments)}if(!d.s(b))throw TypeError("listener must be a function");return c.listener=b,this.aa(a,c),this},c.prototype.removeListener=function(a,b){var c,e,f,g;if(!d.s(b))throw TypeError("listener must be a function");if(!this.V||!this.V[a])return this;if(c=this.V[a],f=c.length,e=-1,c===b||d.s(c.listener)&&c.listener===b)delete this.V[a],this.V.removeListener&&this.$("removeListener",a,b);else if(d.F(c)){for(g=f;g-- >0;)if(c[g]===b||c[g].listener&&c[g].listener===b){e=g;break}if(0>e)return this;1===c.length?(c.length=0,delete this.V[a]):c.splice(e,1),this.V.removeListener&&this.$("removeListener",a,b)}return this},c.prototype.ca=function(a){var b,c;if(!this.V)return this;if(!this.V.removeListener)return 0===arguments.length?this.V={}:this.V[a]&&delete this.V[a],this;if(0===arguments.length){for(b in this.V)"removeListener"!==b&&this.ca(b);return this.ca("removeListener"),this.V={},this}if(c=this.V[a],d.s(c))this.removeListener(a,c);else for(;c.length;)this.removeListener(a,c[c.length-1]);return delete this.V[a],this},c.prototype.da=function(a){var b;return b=this.V&&this.V[a]?d.s(this.V[a])?[this.V[a]]:this.V[a].slice():[]},c.ea=function(a,b){var c;return c=a.V&&a.V[b]?d.s(a.V[b])?1:a.V[b].length:0}},{U:10}],7:[function(a,b,c){function d(a,b){for(var c=0,d=a.length-1;d>=0;d--){var e=a[d];"."===e?a.splice(d,1):".."===e?(a.splice(d,1),c++):c&&(a.splice(d,1),c--)}if(b)for(;c--;c)a.unshift("..");return a}var e=a("__browserify_process"),f=a("util"),g=a("_shims"),h=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,i=function(a){return h.exec(a).slice(1)};c.resolve=function(){for(var a="",b=!1,c=arguments.length-1;c>=-1&&!b;c--){var h=c>=0?arguments[c]:e.fa();if(!f.u(h))throw new TypeError("Arguments to path.resolve must be strings");h&&(a=h+"/"+a,b="/"===h.charAt(0))}return a=d(g.filter(a.split("/"),function(a){return!!a}),!b).join("/"),(b?"/":"")+a||"."},c.normalize=function(a){var b=c.ga(a),e="/"===g.substr(a,-1);return a=d(g.filter(a.split("/"),function(a){return!!a}),!b).join("/"),a||b||(a="."),a&&e&&(a+="/"),(b?"/":"")+a},c.ga=function(a){return"/"===a.charAt(0)},c.join=function(){var a=Array.prototype.slice.call(arguments,0);return c.normalize(g.filter(a,function(a){if(!f.u(a))throw new TypeError("Arguments to path.join must be strings");return a}).join("/"))},c.ha=function(a,b){function d(a){for(var b=0;b<a.length&&""===a[b];b++);for(var c=a.length-1;c>=0&&""===a[c];c--);return b>c?[]:a.slice(b,c-b+1)}a=c.resolve(a).substr(1),b=c.resolve(b).substr(1);for(var e=d(a.split("/")),f=d(b.split("/")),g=Math.min(e.length,f.length),h=g,i=0;g>i;i++)if(e[i]!==f[i]){h=i;break}for(var j=[],i=h;i<e.length;i++)j.push("..");return j=j.concat(f.slice(h)),j.join("/")},c.ia="/",c.ja=":",c.ka=function(a){var b=i(a),c=b[0],d=b[1];return c||d?(d&&(d=d.substr(0,d.length-1)),c+d):"."},c.la=function(a,b){var c=i(a)[2];return b&&c.substr(-1*b.length)===b&&(c=c.substr(0,c.length-b.length)),c},c.ma=function(a){return i(a)[3]}},{k:16,T:3,U:10}],8:[function(a,b,c){function d(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function e(a){return a.charCodeAt(0)}var f=c,g=a("util"),h=a("_shims"),i=a("buffer").na;f.oa=function(a,b){for(var c,d,f,g=new i(a.length),h="CHAR",j=0,k=0;j<=a.length;j++){var l=a.charCodeAt(j);switch(h){case"CHAR":switch(l){case e("%"):c=0,d=0,h="HEX0";break;case e("+"):b&&(l=e(" "));default:g[k++]=l}break;case"HEX0":if(h="HEX1",f=l,e("0")<=l&&l<=e("9"))c=l-e("0");else if(e("a")<=l&&l<=e("f"))c=l-e("a")+10;else{if(!(e("A")<=l&&l<=e("F"))){g[k++]=e("%"),g[k++]=l,h="CHAR";break}c=l-e("A")+10}break;case"HEX1":if(h="CHAR",e("0")<=l&&l<=e("9"))d=l-e("0");else if(e("a")<=l&&l<=e("f"))d=l-e("a")+10;else{if(!(e("A")<=l&&l<=e("F"))){g[k++]=e("%"),g[k++]=f,g[k++]=l;break}d=l-e("A")+10}g[k++]=16*c+d}}return g.slice(0,k-1)},f.unescape=function(a,b){return""+f.oa(a,b)},f.escape=function(a){return encodeURIComponent(a)};var j=function(a){return g.u(a)?a:g.pa(a)?a?"true":"false":g.q(a)&&isFinite(a)?a:""};f.stringify=f.encode=function(a,b,c,d){return b=b||"&",c=c||"=",g.qa(a)&&(a=void 0),g.F(a)?h.map(h.keys(a),function(d){var e=f.escape(j(d))+c;return g.isArray(a[d])?h.map(a[d],function(a){return e+f.escape(j(a))}).join(b):e+f.escape(j(a[d]))}).join(b):d?f.escape(j(d))+c+f.escape(j(a)):""},f.parse=f.decode=function(a,b,c,e){b=b||"&",c=c||"=";var h={};if(!g.u(a)||0===a.length)return h;var i=/\+/g;a=a.split(b);var j=1e3;e&&g.q(e.ra)&&(j=e.ra);var k=a.length;j>0&&k>j&&(k=j);for(var l=0;k>l;++l){var m,n,o,p,q=a[l].replace(i,"%20"),r=q.indexOf(c);r>=0?(m=q.substr(0,r),n=q.substr(r+1)):(m=q,n="");try{o=decodeURIComponent(m),p=decodeURIComponent(n)}catch(a){o=f.unescape(m,!0),p=f.unescape(n,!0)}d(h,o)?g.isArray(h[o])?h[o].push(p):h[o]=[h[o],p]:h[o]=p}return h}},{T:3,buffer:13,U:10}],9:[function(a,b,c){function d(){this.protocol=null,this.sa=null,this.ta=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.ua=null,this.pathname=null,this.path=null,this.href=null}function e(a,b,c){if(a&&j.F(a)&&a instanceof d)return a;var e=new d;return e.parse(a,b,c),e}function f(a){return j.u(a)&&(a=e(a)),a instanceof d?a.format():d.prototype.format.call(a)}function g(a,b){return e(a,!1,!0).resolve(b)}function h(a,b){return a?e(a,!1,!0).va(b):b}var i={encode:function(a){return a}},j=a("util"),k=a("_shims");c.parse=e,c.resolve=g,c.va=h,c.format=f,c.wa=d;var l=/^([a-z0-9.+-]+:)/i,m=/:[0-9]*$/,n=["<",">",'"',"`"," ","\r","\n"," "],o=["{","}","|","\\","^","`"].concat(n),p=["'"].concat(o),q=["%","/","?",";","#"].concat(p),r=["/","?","#"],s=255,t=/^[a-z0-9A-Z_-]{0,63}$/,u=/^([a-z0-9A-Z_-]{0,63})(.*)$/,v={xa:!0,ya:!0},w={xa:!0,ya:!0},x={za:!0,Aa:!0,Ba:!0,Ca:!0,Da:!0,Ea:!0,Fa:!0,Ga:!0,Ha:!0,Ia:!0},y=a("querystring");d.prototype.parse=function(a,b,c){if(!j.u(a))throw new TypeError("Parameter 'url' must be a string, not "+typeof a);var d=a;d=k.trim(d);var e=l.exec(d);if(e){e=e[0];var f=e.toLowerCase();this.protocol=f,d=d.substr(e.length)}if(c||e||d.match(/^\/\/[^@\/]+@[^@\/]+/)){var g="//"===d.substr(0,2);!g||e&&w[e]||(d=d.substr(2),this.sa=!0)}if(!w[e]&&(g||e&&!x[e])){for(var h=-1,m=0;m<r.length;m++){var n=d.indexOf(r[m]);-1!==n&&(-1===h||h>n)&&(h=n)}var o,z;z=-1===h?d.lastIndexOf("@"):d.lastIndexOf("@",h),-1!==z&&(o=d.slice(0,z),d=d.slice(z+1),this.ta=decodeURIComponent(o)),h=-1;for(var m=0;m<q.length;m++){var n=d.indexOf(q[m]);-1!==n&&(-1===h||h>n)&&(h=n)}-1===h&&(h=d.length),this.host=d.slice(0,h),d=d.slice(h),this.Ja(),this.hostname=this.hostname||"";var A="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!A)for(var B=this.hostname.split(/\./),m=0,C=B.length;C>m;m++){var D=B[m];if(D&&!D.match(t)){for(var E="",F=0,G=D.length;G>F;F++)E+=D.charCodeAt(F)>127?"x":D[F];if(!E.match(t)){var H=B.slice(0,m),I=B.slice(m+1),J=D.match(u);J&&(H.push(J[1]),I.unshift(J[2])),I.length&&(d="/"+I.join(".")+d),this.hostname=H.join(".");break}}}if(this.hostname.length>s?this.hostname="":this.hostname=this.hostname.toLowerCase(),!A){for(var K=this.hostname.split("."),L=[],m=0;m<K.length;++m){var M=K[m];L.push(M.match(/[^A-Za-z0-9_-]/)?"xn--"+i.encode(M):M)}this.hostname=L.join(".")}var N=this.port?":"+this.port:"",O=this.hostname||"";this.host=O+N,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==d[0]&&(d="/"+d))}if(!v[f])for(var m=0,C=p.length;C>m;m++){var P=p[m],Q=encodeURIComponent(P);Q===P&&(Q=escape(P)),d=d.split(P).join(Q)}var R=d.indexOf("#");-1!==R&&(this.hash=d.substr(R),d=d.slice(0,R));var S=d.indexOf("?");if(-1!==S?(this.search=d.substr(S),this.ua=d.substr(S+1),b&&(this.ua=y.parse(this.ua)),d=d.slice(0,S)):b&&(this.search="",this.ua={}),d&&(this.pathname=d),x[f]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var N=this.pathname||"",M=this.search||"";this.path=N+M}return this.href=this.format(),this},d.prototype.format=function(){var a=this.ta||"";a&&(a=encodeURIComponent(a),a=a.replace(/%3A/i,":"),a+="@");var b=this.protocol||"",c=this.pathname||"",d=this.hash||"",e=!1,f="";this.host?e=a+this.host:this.hostname&&(e=a+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(e+=":"+this.port)),this.ua&&j.F(this.ua)&&k.keys(this.ua).length&&(f=y.stringify(this.ua));var g=this.search||f&&"?"+f||"";return b&&":"!==k.substr(b,-1)&&(b+=":"),this.sa||(!b||x[b])&&e!==!1?(e="//"+(e||""),c&&"/"!==c.charAt(0)&&(c="/"+c)):e||(e=""),d&&"#"!==d.charAt(0)&&(d="#"+d),g&&"?"!==g.charAt(0)&&(g="?"+g),c=c.replace(/[?#]/g,function(a){return encodeURIComponent(a)}),g=g.replace("#","%23"),b+e+c+g+d},d.prototype.resolve=function(a){return this.va(e(a,!1,!0)).format()},d.prototype.va=function(a){if(j.u(a)){var b=new d;b.parse(a,!1,!0),a=b}var c=new d;if(k.forEach(k.keys(this),function(a){c[a]=this[a]},this),c.hash=a.hash,""===a.href)return c.href=c.format(),c;if(a.sa&&!a.protocol)return k.forEach(k.keys(a),function(b){"protocol"!==b&&(c[b]=a[b])}),x[c.protocol]&&c.hostname&&!c.pathname&&(c.path=c.pathname="/"),c.href=c.format(),c;if(a.protocol&&a.protocol!==c.protocol){if(!x[a.protocol])return k.forEach(k.keys(a),function(b){c[b]=a[b]}),c.href=c.format(),c;if(c.protocol=a.protocol,a.host||w[a.protocol])c.pathname=a.pathname;else{for(var e=(a.pathname||"").split("/");e.length&&!(a.host=e.shift()););a.host||(a.host=""),a.hostname||(a.hostname=""),""!==e[0]&&e.unshift(""),e.length<2&&e.unshift(""),c.pathname=e.join("/")}if(c.search=a.search,c.ua=a.ua,c.host=a.host||"",c.ta=a.ta,c.hostname=a.hostname||a.host,c.port=a.port,c.pathname||c.search){var f=c.pathname||"",g=c.search||"";c.path=f+g}return c.sa=c.sa||a.sa,c.href=c.format(),c}var h=c.pathname&&"/"===c.pathname.charAt(0),i=a.host||a.pathname&&"/"===a.pathname.charAt(0),l=i||h||c.host&&a.pathname,m=l,n=c.pathname&&c.pathname.split("/")||[],e=a.pathname&&a.pathname.split("/")||[],o=c.protocol&&!x[c.protocol];if(o&&(c.hostname="",c.port=null,c.host&&(""===n[0]?n[0]=c.host:n.unshift(c.host)),c.host="",a.protocol&&(a.hostname=null,a.port=null,a.host&&(""===e[0]?e[0]=a.host:e.unshift(a.host)),a.host=null),l=l&&(""===e[0]||""===n[0])),i)c.host=a.host||""===a.host?a.host:c.host,c.hostname=a.hostname||""===a.hostname?a.hostname:c.hostname,c.search=a.search,c.ua=a.ua,n=e;else if(e.length)n||(n=[]),n.pop(),n=n.concat(e),c.search=a.search,c.ua=a.ua;else if(!j.G(a.search)){if(o){c.hostname=c.host=n.shift();var p=c.host&&c.host.indexOf("@")>0?c.host.split("@"):!1;p&&(c.ta=p.shift(),c.host=c.hostname=p.shift())}return c.search=a.search,c.ua=a.ua,j.qa(c.pathname)&&j.qa(c.search)||(c.path=(c.pathname?c.pathname:"")+(c.search?c.search:"")),c.href=c.format(),c}if(!n.length)return c.pathname=null,c.search?c.path="/"+c.search:c.path=null,c.href=c.format(),c;for(var q=n.slice(-1)[0],r=(c.host||a.host)&&("."===q||".."===q)||""===q,s=0,t=n.length;t>=0;t--)q=n[t],"."==q?n.splice(t,1):".."===q?(n.splice(t,1),s++):s&&(n.splice(t,1),s--);if(!l&&!m)for(;s--;s)n.unshift("..");!l||""===n[0]||n[0]&&"/"===n[0].charAt(0)||n.unshift(""),r&&"/"!==k.substr(n.join("/"),-1)&&n.push("");var u=""===n[0]||n[0]&&"/"===n[0].charAt(0);if(o){c.hostname=c.host=u?"":n.length?n.shift():"";var p=c.host&&c.host.indexOf("@")>0?c.host.split("@"):!1;p&&(c.ta=p.shift(),c.host=c.hostname=p.shift())}return l=l||c.host&&n.length,l&&!u&&n.unshift(""),n.length?c.pathname=n.join("/"):(c.pathname=null,c.path=null),j.qa(c.pathname)&&j.qa(c.search)||(c.path=(c.pathname?c.pathname:"")+(c.search?c.search:"")),c.ta=a.ta||c.ta,c.sa=c.sa||a.sa,c.href=c.format(),c},d.prototype.Ja=function(){var a=this.host,b=m.exec(a);b&&(b=b[0],":"!==b&&(this.port=b.substr(1)),a=a.substr(0,a.length-b.length)),a&&(this.hostname=a)}},{T:3,Ka:8,U:10}],10:[function(a,b,c){function d(a,b){var d={La:[],Ma:f};return arguments.length>=3&&(d.Na=arguments[2]),arguments.length>=4&&(d.Oa=arguments[3]),o(b)?d.Pa=b:b&&c.Qa(d,b),u(d.Pa)&&(d.Pa=!1),u(d.Na)&&(d.Na=2),u(d.Oa)&&(d.Oa=!1),u(d.Ra)&&(d.Ra=!0),d.Oa&&(d.Ma=e),h(d,a,d.Na)}function e(a,b){var c=d.Sa[b];return c?"["+d.Oa[c][0]+"m"+a+"["+d.Oa[c][1]+"m":a}function f(a){return a}function g(a){var b={};return G.forEach(a,function(a){b[a]=!0}),b}function h(a,b,d){if(a.Ra&&b&&z(b.Ta)&&b.Ta!==c.Ta&&(!b.constructor||b.constructor.prototype!==b)){var e=b.Ta(d);return s(e)||(e=h(a,e,d)),e}var f=i(a,b);if(f)return f;var o=G.keys(b),p=g(o);if(a.Pa&&(o=G.getOwnPropertyNames(b)),0===o.length){if(z(b)){var q=b.name?": "+b.name:"";return a.Ma("[Function"+q+"]","special")}if(v(b))return a.Ma(RegExp.prototype.toString.call(b),"regexp");if(x(b))return a.Ma(Date.prototype.toString.call(b),"date");if(y(b))return j(b)}var r="",t=!1,u=["{","}"];if(n(b)&&(t=!0,u=["[","]"]),z(b)){var w=b.name?": "+b.name:"";r=" [Function"+w+"]"}if(v(b)&&(r=" "+RegExp.prototype.toString.call(b)),x(b)&&(r=" "+Date.prototype.toUTCString.call(b)),y(b)&&(r=" "+j(b)),0===o.length&&(!t||0==b.length))return u[0]+r+u[1];if(0>d)return v(b)?a.Ma(RegExp.prototype.toString.call(b),"regexp"):a.Ma("[Object]","special");a.La.push(b);var A;return A=t?k(a,b,d,p,o):o.map(function(c){return l(a,b,d,p,c,t)}),a.La.pop(),m(A,r,u)}function i(a,b){if(u(b))return a.Ma("undefined","undefined");if(s(b)){var c="'"+JSON.stringify(b).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return a.Ma(c,"string")}return r(b)?a.Ma(""+b,"number"):o(b)?a.Ma(""+b,"boolean"):p(b)?a.Ma("null","null"):void 0}function j(a){return"["+Error.prototype.toString.call(a)+"]"}function k(a,b,c,d,e){for(var f=[],g=0,h=b.length;h>g;++g)F(b,g+"")?f.push(l(a,b,c,d,g+"",!0)):f.push("");return G.forEach(e,function(e){e.match(/^\d+$/)||f.push(l(a,b,c,d,e,!0))}),f}function l(a,b,c,d,e,f){var g,i,j;if(j=G.getOwnPropertyDescriptor(b,e)||{value:b[e]},j.get?i=j.set?a.Ma("[Getter/Setter]","special"):a.Ma("[Getter]","special"):j.set&&(i=a.Ma("[Setter]","special")),F(d,e)||(g="["+e+"]"),i||(G.indexOf(a.La,j.value)<0?(i=p(c)?h(a,j.value,null):h(a,j.value,c-1),i.indexOf("\n")>-1&&(i=f?i.split("\n").map(function(a){return" "+a}).join("\n").substr(2):"\n"+i.split("\n").map(function(a){return" "+a}).join("\n"))):i=a.Ma("[Circular]","special")),u(g)){if(f&&e.match(/^\d+$/))return i;g=JSON.stringify(""+e),g.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(g=g.substr(1,g.length-2),g=a.Ma(g,"name")):(g=g.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),g=a.Ma(g,"string"))}return g+": "+i}function m(a,b,c){var d=0,e=G.reduce(a,function(a,b){return d++,b.indexOf("\n")>=0&&d++,a+b.replace(/\u001b\[\d\d?m/g,"").length+1},0);return e>60?c[0]+(""===b?"":b+"\n ")+" "+a.join(",\n ")+" "+c[1]:c[0]+b+" "+a.join(", ")+" "+c[1]}function n(a){return G.isArray(a)}function o(a){return"boolean"==typeof a}function p(a){return null===a}function q(a){return null==a}function r(a){return"number"==typeof a}function s(a){return"string"==typeof a}function t(a){return"symbol"==typeof a}function u(a){return void 0===a}function v(a){return w(a)&&"[object RegExp]"===C(a)}function w(a){return"object"==typeof a&&a}function x(a){return w(a)&&"[object Date]"===C(a)}function y(a){return w(a)&&"[object Error]"===C(a)}function z(a){return"function"==typeof a}function A(a){return null===a||"boolean"==typeof a||"number"==typeof a||"string"==typeof a||"symbol"==typeof a||void 0===a}function B(a){return a&&"object"==typeof a&&"function"==typeof a.Ua&&"function"==typeof a.fill&&"function"==typeof a.Va}function C(a){return Object.prototype.toString.call(a)}function D(a){return 10>a?"0"+a.toString(10):a.toString(10)}function E(){var a=new Date,b=[D(a.getHours()),D(a.getMinutes()),D(a.getSeconds())].join(":");return[a.getDate(),I[a.getMonth()],b].join(" ")}function F(a,b){return Object.prototype.hasOwnProperty.call(a,b)}var G=a("_shims"),H=/%[sdj%]/g;c.format=function(a){if(!s(a)){for(var b=[],c=0;c<arguments.length;c++)b.push(d(arguments[c]));return b.join(" ")}for(var c=1,e=arguments,f=e.length,g=(a+"").replace(H,function(a){if("%%"===a)return"%";if(c>=f)return a;switch(a){case"%s":return e[c++]+"";case"%d":return+e[c++];case"%j":try{return JSON.stringify(e[c++])}catch(a){return"[Circular]"}default:return a}}),h=e[c];f>c;h=e[++c])g+=p(h)||!w(h)?" "+h:" "+d(h);return g},c.Ta=d,d.Oa={bold:[1,22],Wa:[3,23],Xa:[4,24],inverse:[7,27],Ya:[37,39],Za:[90,39],$a:[30,39],blue:[34,39],_a:[36,39],green:[32,39],ab:[35,39],red:[31,39],bb:[33,39]},d.Sa={cb:"cyan",number:"yellow",eb:"yellow",undefined:"grey",fb:"bold",gb:"green",hb:"magenta",ib:"red"},c.isArray=n,c.pa=o,c.qa=p,c.G=q,c.q=r,c.u=s,c.jb=t,c.p=u,c.t=v,c.F=w,c.D=x,c.kb=y,c.s=z,c.lb=A,c.isBuffer=B;var I=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];c.log=function(){console.log("%s - %s",E(),c.format.apply(c,arguments))},c.H=function(a,b){a.mb=b,a.prototype=G.create(b.prototype,{constructor:{value:a,nb:!1,ob:!0,pb:!0}})},c.Qa=function(a,b){if(!b||!w(b))return a;for(var c=G.keys(b),d=c.length;d--;)a[c[d]]=b[c[d]];return a}},{T:3}],11:[function(){},{}],12:[function(a,b,c){c.qb=function(a,b,c,d,e){var f,g,h=8*e-d-1,i=(1<<h)-1,j=i>>1,k=-7,l=c?0:e-1,m=c?1:-1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?NaN:(n?-1:1)*(1/0);g+=Math.pow(2,d),f-=j}return(n?-1:1)*g*Math.pow(2,f-d)},c.rb=function(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<<j)-1,l=k>>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?f-1:0,o=d?-1:1,p=0>b||0===b&&0>1/b?1:0;for(b=Math.abs(b),isNaN(b)||b===1/0?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<<e|h,j+=e;j>0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p}},{}],13:[function(a,b,c){function d(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")}function e(b,c,f){if(E||(E=a("assert")),!(this instanceof e))return new e(b,c,f);if(this.parent=this,this.offset=0,"base64"==c&&"string"==typeof b)for(b=d(b);b.length%4!=0;)b+="=";var h;if("number"==typeof f){this.length=g(c);for(var j=0;j<this.length;j++)this[j]=b.get(j+f)}else{switch(h=typeof b){case"number":this.length=g(b);break;case"string":this.length=e.byteLength(b,c);break;case"object":this.length=g(b.length);break;default:throw new TypeError("First argument needs to be a number, array or string.")}if(i(b))for(var j=0;j<this.length;j++)b instanceof e?this[j]=b.sb(j):this[j]=(b[j]%256+256)%256;else if("string"==h)this.length=this.write(b,0,c);else if("number"===h)for(var j=0;j<this.length;j++)this[j]=0}}function f(a,b,c){return"number"!=typeof a?c:(a=~~a,a>=b?b:a>=0?a:(a+=b,a>=0?a:0))}function g(a){return a=~~Math.ceil(+a),0>a?0:a}function h(a){return(Array.isArray||function(a){return"[object Array]"=={}.toString.apply(a)})(a)}function i(a){return h(a)||e.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length}function j(a){return 16>a?"0"+a.toString(16):a.toString(16)}function k(a){for(var b=[],c=0;c<a.length;c++)if(a.charCodeAt(c)<=127)b.push(a.charCodeAt(c));else for(var d=encodeURIComponent(a.charAt(c)).substr(1).split("%"),e=0;e<d.length;e++)b.push(parseInt(d[e],16));return b}function l(a){for(var b=[],c=0;c<a.length;c++)b.push(255&a.charCodeAt(c));return b}function m(b){return a("base64-js").l(b)}function n(a,b,c,d){for(var e=0;d>e&&!(e+c>=b.length||e>=a.length);)b[e+c]=a[e],e++;return e}function o(a){try{return decodeURIComponent(a)}catch(a){return String.fromCharCode(65533)}}function p(a,b,c,d){var e=0;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+1<a.length,"Trying to read beyond buffer length")),b>=a.length?0:(c?(e=a[b]<<8,b+1<a.length&&(e|=a[b+1])):(e=a[b],b+1<a.length&&(e|=a[b+1]<<8)),e)}function q(a,b,c,d){var e=0;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+3<a.length,"Trying to read beyond buffer length")),b>=a.length?0:(c?(b+1<a.length&&(e=a[b+1]<<16),b+2<a.length&&(e|=a[b+2]<<8),b+3<a.length&&(e|=a[b+3]),e+=a[b]<<24>>>0):(b+2<a.length&&(e=a[b+2]<<16),b+1<a.length&&(e|=a[b+1]<<8),e|=a[b],b+3<a.length&&(e+=a[b+3]<<24>>>0)),e)}function r(a,b,c,d){var e,f;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+1<a.length,"Trying to read beyond buffer length")),f=p(a,b,c,d),e=32768&f,e?-1*(65535-f+1):f}function s(a,b,c,d){var e,f;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+3<a.length,"Trying to read beyond buffer length")),f=q(a,b,c,d),e=2147483648&f,e?-1*(4294967295-f+1):f}function t(b,c,d,e){return e||(E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(c+3<b.length,"Trying to read beyond buffer length")),a("./buffer_ieee754").qb(b,c,d,23,4)}function u(b,c,d,e){return e||(E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(c+7<b.length,"Trying to read beyond buffer length")),a("./buffer_ieee754").qb(b,c,d,52,8)}function v(a,b){E.ok("number"==typeof a,"cannot write a non-number as a number"),E.ok(a>=0,"specified a negative value for writing an unsigned value"),E.ok(b>=a,"value is larger than maximum value for type"),E.ok(Math.floor(a)===a,"value has a fractional component")}function w(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+1<a.length,"trying to write beyond buffer length"),v(b,65535));for(var f=0;f<Math.min(a.length-c,2);f++)a[c+f]=(b&255<<8*(d?1-f:f))>>>8*(d?1-f:f)}function x(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+3<a.length,"trying to write beyond buffer length"),v(b,4294967295));for(var f=0;f<Math.min(a.length-c,4);f++)a[c+f]=b>>>8*(d?3-f:f)&255}function y(a,b,c){E.ok("number"==typeof a,"cannot write a non-number as a number"),E.ok(b>=a,"value larger than maximum allowed value"),E.ok(a>=c,"value smaller than minimum allowed value"),E.ok(Math.floor(a)===a,"value has a fractional component")}function z(a,b,c){E.ok("number"==typeof a,"cannot write a non-number as a number"),E.ok(b>=a,"value larger than maximum allowed value"),E.ok(a>=c,"value smaller than minimum allowed value")}function A(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+1<a.length,"Trying to write beyond buffer length"),y(b,32767,-32768)),b>=0?w(a,b,c,d,e):w(a,65535+b+1,c,d,e)}function B(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+3<a.length,"Trying to write beyond buffer length"),y(b,2147483647,-2147483648)),b>=0?x(a,b,c,d,e):x(a,4294967295+b+1,c,d,e);
}function C(b,c,d,e,f){f||(E.ok(void 0!==c&&null!==c,"missing value"),E.ok("boolean"==typeof e,"missing or invalid endian"),E.ok(void 0!==d&&null!==d,"missing offset"),E.ok(d+3<b.length,"Trying to write beyond buffer length"),z(c,3.4028234663852886e38,-3.4028234663852886e38)),a("./buffer_ieee754").rb(b,c,d,e,23,4)}function D(b,c,d,e,f){f||(E.ok(void 0!==c&&null!==c,"missing value"),E.ok("boolean"==typeof e,"missing or invalid endian"),E.ok(void 0!==d&&null!==d,"missing offset"),E.ok(d+7<b.length,"Trying to write beyond buffer length"),z(c,1.7976931348623157e308,-1.7976931348623157e308)),a("./buffer_ieee754").rb(b,c,d,e,52,8)}var E;c.na=e,c.tb=e,e.ub=8192,c.vb=50,e.prototype.get=function(a){if(0>a||a>=this.length)throw Error("oob");return this[a]},e.prototype.set=function(a,b){if(0>a||a>=this.length)throw Error("oob");return this[a]=b},e.byteLength=function(a,b){switch(b||"utf8"){case"hex":return a.length/2;case"utf8":case"utf-8":return k(a).length;case"ascii":case"binary":return a.length;case"base64":return m(a).length;default:throw Error("Unknown encoding")}},e.prototype.wb=function(a,b,c){return e.xb=n(k(a),this,b,c)},e.prototype.yb=function(a,b,c){return e.xb=n(l(a),this,b,c)},e.prototype.zb=e.prototype.yb,e.prototype.Ab=function(a,b,c){return e.xb=n(m(a),this,b,c)},e.prototype.Bb=function(){var b=Array.prototype.slice.apply(this,arguments);return a("base64-js").m(b)},e.prototype.Cb=function(){for(var a=Array.prototype.slice.apply(this,arguments),b="",c="",d=0;d<a.length;)a[d]<=127?(b+=o(c)+String.fromCharCode(a[d]),c=""):c+="%"+a[d].toString(16),d++;return b+o(c)},e.prototype.Db=function(){for(var a=Array.prototype.slice.apply(this,arguments),b="",c=0;c<a.length;c++)b+=String.fromCharCode(a[c]);return b},e.prototype.Va=e.prototype.Db,e.prototype.Ta=function(){for(var a=[],b=this.length,d=0;b>d;d++)if(a[d]=j(this[d]),d==c.vb){a[d+1]="...";break}return"<Buffer "+a.join(" ")+">"},e.prototype.Eb=function(a,b){var c=this.length;(!a||0>a)&&(a=0),(!b||0>b||b>c)&&(b=c);for(var d="",e=a;b>e;e++)d+=j(this[e]);return d},e.prototype.toString=function(a,b,c){if(a=((a||"utf8")+"").toLowerCase(),b=+b||0,void 0===c&&(c=this.length),+c==b)return"";switch(a){case"hex":return this.Eb(b,c);case"utf8":case"utf-8":return this.Cb(b,c);case"ascii":return this.Db(b,c);case"binary":return this.Va(b,c);case"base64":return this.Bb(b,c);case"ucs2":case"ucs-2":return this.ucs2Slice(b,c);default:throw Error("Unknown encoding")}},e.prototype.Fb=function(a,b,c){b=+b||0;var d=this.length-b;c?(c=+c,c>d&&(c=d)):c=d;var f=a.length;if(f%2)throw Error("Invalid hex string");c>f/2&&(c=f/2);for(var g=0;c>g;g++){var h=parseInt(a.substr(2*g,2),16);if(isNaN(h))throw Error("Invalid hex string");this[b+g]=h}return e.xb=2*g,g},e.prototype.write=function(a,b,c,d){if(isFinite(b))isFinite(c)||(d=c,c=void 0);else{var e=d;d=b,b=c,c=e}b=+b||0;var f=this.length-b;switch(c?(c=+c,c>f&&(c=f)):c=f,d=((d||"utf8")+"").toLowerCase()){case"hex":return this.Fb(a,b,c);case"utf8":case"utf-8":return this.wb(a,b,c);case"ascii":return this.yb(a,b,c);case"binary":return this.zb(a,b,c);case"base64":return this.Ab(a,b,c);case"ucs2":case"ucs-2":return this.ucs2Write(a,b,c);default:throw Error("Unknown encoding")}},e.prototype.slice=function(a,b){var c=this.length;return a=f(a,c,0),b=f(b,c,c),new e(this,b-a,+a)},e.prototype.Ua=function(a,b,c,d){var e=this;if(c||(c=0),(void 0===d||isNaN(d))&&(d=this.length),b||(b=0),c>d)throw Error("sourceEnd < sourceStart");if(d===c)return 0;if(0==a.length||0==e.length)return 0;if(0>b||b>=a.length)throw Error("targetStart out of bounds");if(0>c||c>=e.length)throw Error("sourceStart out of bounds");if(0>d||d>e.length)throw Error("sourceEnd out of bounds");d>this.length&&(d=this.length),a.length-b<d-c&&(d=a.length-b+c);for(var f=[],g=c;d>g;g++)E.ok(void 0!==this[g],"copying undefined buffer bytes!"),f.push(this[g]);for(var g=b;g<b+f.length;g++)a[g]=f[g-b]},e.prototype.fill=function(a,b,c){if(a||(a=0),b||(b=0),c||(c=this.length),"string"==typeof a&&(a=a.charCodeAt(0)),"number"!=typeof a||isNaN(a))throw Error("value is not a number");if(b>c)throw Error("end < start");if(c===b)return 0;if(0==this.length)return 0;if(0>b||b>=this.length)throw Error("start out of bounds");if(0>c||c>this.length)throw Error("end out of bounds");for(var d=b;c>d;d++)this[d]=a},e.isBuffer=function(a){return a instanceof e},e.concat=function(a,b){if(!h(a))throw Error("Usage: Buffer.concat(list, [totalLength])\n list should be an Array.");if(0===a.length)return new e(0);if(1===a.length)return a[0];if("number"!=typeof b){b=0;for(var c=0;c<a.length;c++){var d=a[c];b+=d.length}}for(var f=new e(b),g=0,c=0;c<a.length;c++){var d=a[c];d.Ua(f,g),g+=d.length}return f},e.Gb=function(a){switch((a+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},e.prototype.sb=function(a,b){var c=this;return b||(E.ok(void 0!==a&&null!==a,"missing offset"),E.ok(a<c.length,"Trying to read beyond buffer length")),a>=c.length?void 0:c[a]},e.prototype.Hb=function(a,b){return p(this,a,!1,b)},e.prototype.Ib=function(a,b){return p(this,a,!0,b)},e.prototype.Jb=function(a,b){return q(this,a,!1,b)},e.prototype.Kb=function(a,b){return q(this,a,!0,b)},e.prototype.Lb=function(a,b){var c,d=this;return b||(E.ok(void 0!==a&&null!==a,"missing offset"),E.ok(a<d.length,"Trying to read beyond buffer length")),a>=d.length?void 0:(c=128&d[a],c?-1*(255-d[a]+1):d[a])},e.prototype.Mb=function(a,b){return r(this,a,!1,b)},e.prototype.Nb=function(a,b){return r(this,a,!0,b)},e.prototype.Ob=function(a,b){return s(this,a,!1,b)},e.prototype.Pb=function(a,b){return s(this,a,!0,b)},e.prototype.Qb=function(a,b){return t(this,a,!1,b)},e.prototype.Rb=function(a,b){return t(this,a,!0,b)},e.prototype.Sb=function(a,b){return u(this,a,!1,b)},e.prototype.Tb=function(a,b){return u(this,a,!0,b)},e.prototype.Ub=function(a,b,c){var d=this;c||(E.ok(void 0!==a&&null!==a,"missing value"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b<d.length,"trying to write beyond buffer length"),v(a,255)),b<d.length&&(d[b]=a)},e.prototype.Vb=function(a,b,c){w(this,a,b,!1,c)},e.prototype.Wb=function(a,b,c){w(this,a,b,!0,c)},e.prototype.Xb=function(a,b,c){x(this,a,b,!1,c)},e.prototype.Yb=function(a,b,c){x(this,a,b,!0,c)},e.prototype.Zb=function(a,b,c){var d=this;c||(E.ok(void 0!==a&&null!==a,"missing value"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b<d.length,"Trying to write beyond buffer length"),y(a,127,-128)),a>=0?d.Ub(a,b,c):d.Ub(255+a+1,b,c)},e.prototype.$b=function(a,b,c){A(this,a,b,!1,c)},e.prototype._b=function(a,b,c){A(this,a,b,!0,c)},e.prototype.ac=function(a,b,c){B(this,a,b,!1,c)},e.prototype.bc=function(a,b,c){B(this,a,b,!0,c)},e.prototype.cc=function(a,b,c){C(this,a,b,!1,c)},e.prototype.dc=function(a,b,c){C(this,a,b,!0,c)},e.prototype.ec=function(a,b,c){D(this,a,b,!1,c)},e.prototype.fc=function(a,b,c){D(this,a,b,!0,c)}},{gc:12,assert:4,hc:2}],14:[function(a,b){a=function b(c,d,e){function f(h,i){if(!d[h]){if(!c[h]){var j="function"==typeof a&&a;if(!i&&j)return j(h,!0);if(g)return g(h,!0);throw Error("Cannot find module '"+h+"'")}var k=d[h]={g:{}};c[h][0].call(k.g,function(a){var b=c[h][1][a];return f(b?b:a)},k,k.g,b,c,d,e)}return d[h].g}for(var g="function"==typeof a&&a,h=0;h<e.length;h++)f(e[h]);return f}({1:[function(a,b,c){c.qb=function(a,b,c,d,e){var f,g,h=8*e-d-1,i=(1<<h)-1,j=i>>1,k=-7,l=c?0:e-1,m=c?1:-1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?NaN:(n?-1:1)*(1/0);g+=Math.pow(2,d),f-=j}return(n?-1:1)*g*Math.pow(2,f-d)},c.rb=function(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<<j)-1,l=k>>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?f-1:0,o=d?-1:1,p=0>b||0===b&&0>1/b?1:0;for(b=Math.abs(b),isNaN(b)||b===1/0?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<<e|h,j+=e;j>0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p}},{}],ic:[function(a,b,c){function d(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")}function e(b,c,f){if(E||(E=a("assert")),!(this instanceof e))return new e(b,c,f);if(this.parent=this,this.offset=0,"base64"==c&&"string"==typeof b)for(b=d(b);b.length%4!=0;)b+="=";var h;if("number"==typeof f){this.length=g(c);for(var j=0;j<this.length;j++)this[j]=b.get(j+f)}else{switch(h=typeof b){case"number":this.length=g(b);break;case"string":this.length=e.byteLength(b,c);break;case"object":this.length=g(b.length);break;default:throw Error("First argument needs to be a number, array or string.")}if(i(b))for(var j=0;j<this.length;j++)b instanceof e?this[j]=b.sb(j):this[j]=b[j];else if("string"==h)this.length=this.write(b,0,c);else if("number"===h)for(var j=0;j<this.length;j++)this[j]=0}}function f(a,b,c){return"number"!=typeof a?c:(a=~~a,a>=b?b:a>=0?a:(a+=b,a>=0?a:0))}function g(a){return a=~~Math.ceil(+a),0>a?0:a}function h(a){return(Array.isArray||function(a){return"[object Array]"=={}.toString.apply(a)})(a)}function i(a){return h(a)||e.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length}function j(a){return 16>a?"0"+a.toString(16):a.toString(16)}function k(a){for(var b=[],c=0;c<a.length;c++)if(a.charCodeAt(c)<=127)b.push(a.charCodeAt(c));else for(var d=encodeURIComponent(a.charAt(c)).substr(1).split("%"),e=0;e<d.length;e++)b.push(parseInt(d[e],16));return b}function l(a){for(var b=[],c=0;c<a.length;c++)b.push(255&a.charCodeAt(c));return b}function m(b){return a("base64-js").l(b)}function n(a,b,c,d){for(var e=0;d>e&&!(e+c>=b.length||e>=a.length);)b[e+c]=a[e],e++;return e}function o(a){try{return decodeURIComponent(a)}catch(a){return String.fromCharCode(65533)}}function p(a,b,c,d){var e=0;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+1<a.length,"Trying to read beyond buffer length")),b>=a.length?0:(c?(e=a[b]<<8,b+1<a.length&&(e|=a[b+1])):(e=a[b],b+1<a.length&&(e|=a[b+1]<<8)),e)}function q(a,b,c,d){var e=0;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+3<a.length,"Trying to read beyond buffer length")),b>=a.length?0:(c?(b+1<a.length&&(e=a[b+1]<<16),b+2<a.length&&(e|=a[b+2]<<8),b+3<a.length&&(e|=a[b+3]),e+=a[b]<<24>>>0):(b+2<a.length&&(e=a[b+2]<<16),b+1<a.length&&(e|=a[b+1]<<8),e|=a[b],b+3<a.length&&(e+=a[b+3]<<24>>>0)),e)}function r(a,b,c,d){var e,f;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+1<a.length,"Trying to read beyond buffer length")),f=p(a,b,c,d),e=32768&f,e?-1*(65535-f+1):f}function s(a,b,c,d){var e,f;return d||(E.ok("boolean"==typeof c,"missing or invalid endian"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b+3<a.length,"Trying to read beyond buffer length")),f=q(a,b,c,d),e=2147483648&f,e?-1*(4294967295-f+1):f}function t(b,c,d,e){return e||(E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(c+3<b.length,"Trying to read beyond buffer length")),a("./buffer_ieee754").qb(b,c,d,23,4)}function u(b,c,d,e){return e||(E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(c+7<b.length,"Trying to read beyond buffer length")),a("./buffer_ieee754").qb(b,c,d,52,8)}function v(a,b){E.ok("number"==typeof a,"cannot write a non-number as a number"),E.ok(a>=0,"specified a negative value for writing an unsigned value"),E.ok(b>=a,"value is larger than maximum value for type"),E.ok(Math.floor(a)===a,"value has a fractional component")}function w(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+1<a.length,"trying to write beyond buffer length"),v(b,65535));for(var f=0;f<Math.min(a.length-c,2);f++)a[c+f]=(b&255<<8*(d?1-f:f))>>>8*(d?1-f:f)}function x(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+3<a.length,"trying to write beyond buffer length"),v(b,4294967295));for(var f=0;f<Math.min(a.length-c,4);f++)a[c+f]=b>>>8*(d?3-f:f)&255}function y(a,b,c){E.ok("number"==typeof a,"cannot write a non-number as a number"),E.ok(b>=a,"value larger than maximum allowed value"),E.ok(a>=c,"value smaller than minimum allowed value"),E.ok(Math.floor(a)===a,"value has a fractional component")}function z(a,b,c){E.ok("number"==typeof a,"cannot write a non-number as a number"),E.ok(b>=a,"value larger than maximum allowed value"),E.ok(a>=c,"value smaller than minimum allowed value")}function A(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+1<a.length,"Trying to write beyond buffer length"),y(b,32767,-32768)),b>=0?w(a,b,c,d,e):w(a,65535+b+1,c,d,e)}function B(a,b,c,d,e){e||(E.ok(void 0!==b&&null!==b,"missing value"),E.ok("boolean"==typeof d,"missing or invalid endian"),E.ok(void 0!==c&&null!==c,"missing offset"),E.ok(c+3<a.length,"Trying to write beyond buffer length"),y(b,2147483647,-2147483648)),b>=0?x(a,b,c,d,e):x(a,4294967295+b+1,c,d,e)}function C(b,c,d,e,f){f||(E.ok(void 0!==c&&null!==c,"missing value"),E.ok("boolean"==typeof e,"missing or invalid endian"),E.ok(void 0!==d&&null!==d,"missing offset"),E.ok(d+3<b.length,"Trying to write beyond buffer length"),z(c,3.4028234663852886e38,-3.4028234663852886e38)),a("./buffer_ieee754").rb(b,c,d,e,23,4)}function D(b,c,d,e,f){f||(E.ok(void 0!==c&&null!==c,"missing value"),E.ok("boolean"==typeof e,"missing or invalid endian"),E.ok(void 0!==d&&null!==d,"missing offset"),E.ok(d+7<b.length,"Trying to write beyond buffer length"),z(c,1.7976931348623157e308,-1.7976931348623157e308)),a("./buffer_ieee754").rb(b,c,d,e,52,8)}var E;c.na=e,c.tb=e,e.ub=8192,c.vb=50,e.prototype.get=function(a){if(0>a||a>=this.length)throw Error("oob");return this[a]},e.prototype.set=function(a,b){if(0>a||a>=this.length)throw Error("oob");return this[a]=b},e.byteLength=function(a,b){switch(b||"utf8"){case"hex":return a.length/2;case"utf8":case"utf-8":return k(a).length;case"ascii":case"binary":return a.length;case"base64":return m(a).length;default:throw Error("Unknown encoding")}},e.prototype.wb=function(a,b,c){return e.xb=n(k(a),this,b,c)},e.prototype.yb=function(a,b,c){return e.xb=n(l(a),this,b,c)},e.prototype.zb=e.prototype.yb,e.prototype.Ab=function(a,b,c){return e.xb=n(m(a),this,b,c)},e.prototype.Bb=function(){var b=Array.prototype.slice.apply(this,arguments);return a("base64-js").m(b)},e.prototype.Cb=function(){for(var a=Array.prototype.slice.apply(this,arguments),b="",c="",d=0;d<a.length;)a[d]<=127?(b+=o(c)+String.fromCharCode(a[d]),c=""):c+="%"+a[d].toString(16),d++;return b+o(c)},e.prototype.Db=function(){for(var a=Array.prototype.slice.apply(this,arguments),b="",c=0;c<a.length;c++)b+=String.fromCharCode(a[c]);return b},e.prototype.Va=e.prototype.Db,e.prototype.Ta=function(){for(var a=[],b=this.length,d=0;b>d;d++)if(a[d]=j(this[d]),d==c.vb){a[d+1]="...";break}return"<Buffer "+a.join(" ")+">"},e.prototype.Eb=function(a,b){var c=this.length;(!a||0>a)&&(a=0),(!b||0>b||b>c)&&(b=c);for(var d="",e=a;b>e;e++)d+=j(this[e]);return d},e.prototype.toString=function(a,b,c){if(a=((a||"utf8")+"").toLowerCase(),b=+b||0,void 0===c&&(c=this.length),+c==b)return"";switch(a){case"hex":return this.Eb(b,c);case"utf8":case"utf-8":return this.Cb(b,c);case"ascii":return this.Db(b,c);case"binary":return this.Va(b,c);case"base64":return this.Bb(b,c);case"ucs2":case"ucs-2":return this.ucs2Slice(b,c);default:throw Error("Unknown encoding")}},e.prototype.Fb=function(a,b,c){b=+b||0;var d=this.length-b;c?(c=+c,c>d&&(c=d)):c=d;var f=a.length;if(f%2)throw Error("Invalid hex string");c>f/2&&(c=f/2);for(var g=0;c>g;g++){var h=parseInt(a.substr(2*g,2),16);if(isNaN(h))throw Error("Invalid hex string");this[b+g]=h}return e.xb=2*g,g},e.prototype.write=function(a,b,c,d){if(isFinite(b))isFinite(c)||(d=c,c=void 0);else{var e=d;d=b,b=c,c=e}b=+b||0;var f=this.length-b;switch(c?(c=+c,c>f&&(c=f)):c=f,d=((d||"utf8")+"").toLowerCase()){case"hex":return this.Fb(a,b,c);case"utf8":case"utf-8":return this.wb(a,b,c);case"ascii":return this.yb(a,b,c);case"binary":return this.zb(a,b,c);case"base64":return this.Ab(a,b,c);case"ucs2":case"ucs-2":return this.ucs2Write(a,b,c);default:throw Error("Unknown encoding")}},e.prototype.slice=function(a,b){var c=this.length;return a=f(a,c,0),b=f(b,c,c),new e(this,b-a,+a)},e.prototype.Ua=function(a,b,c,d){var e=this;if(c||(c=0),(void 0===d||isNaN(d))&&(d=this.length),b||(b=0),c>d)throw Error("sourceEnd < sourceStart");if(d===c)return 0;if(0==a.length||0==e.length)return 0;if(0>b||b>=a.length)throw Error("targetStart out of bounds");if(0>c||c>=e.length)throw Error("sourceStart out of bounds");if(0>d||d>e.length)throw Error("sourceEnd out of bounds");d>this.length&&(d=this.length),a.length-b<d-c&&(d=a.length-b+c);for(var f=[],g=c;d>g;g++)E.ok(void 0!==this[g],"copying undefined buffer bytes!"),f.push(this[g]);for(var g=b;g<b+f.length;g++)a[g]=f[g-b]},e.prototype.fill=function(a,b,c){if(a||(a=0),b||(b=0),c||(c=this.length),"string"==typeof a&&(a=a.charCodeAt(0)),"number"!=typeof a||isNaN(a))throw Error("value is not a number");if(b>c)throw Error("end < start");if(c===b)return 0;if(0==this.length)return 0;if(0>b||b>=this.length)throw Error("start out of bounds");if(0>c||c>this.length)throw Error("end out of bounds");for(var d=b;c>d;d++)this[d]=a},e.isBuffer=function(a){return a instanceof e||a instanceof e},e.concat=function(a,b){if(!h(a))throw Error("Usage: Buffer.concat(list, [totalLength])\n list should be an Array.");if(0===a.length)return new e(0);if(1===a.length)return a[0];if("number"!=typeof b){b=0;for(var c=0;c<a.length;c++){var d=a[c];b+=d.length}}for(var f=new e(b),g=0,c=0;c<a.length;c++){var d=a[c];d.Ua(f,g),g+=d.length}return f},e.Gb=function(a){switch((a+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}},e.prototype.sb=function(a,b){var c=this;return b||(E.ok(void 0!==a&&null!==a,"missing offset"),E.ok(a<c.length,"Trying to read beyond buffer length")),a>=c.length?void 0:c[a]},e.prototype.Hb=function(a,b){return p(this,a,!1,b)},e.prototype.Ib=function(a,b){return p(this,a,!0,b)},e.prototype.Jb=function(a,b){return q(this,a,!1,b)},e.prototype.Kb=function(a,b){return q(this,a,!0,b)},e.prototype.Lb=function(a,b){var c,d=this;return b||(E.ok(void 0!==a&&null!==a,"missing offset"),E.ok(a<d.length,"Trying to read beyond buffer length")),a>=d.length?void 0:(c=128&d[a],c?-1*(255-d[a]+1):d[a])},e.prototype.Mb=function(a,b){return r(this,a,!1,b)},e.prototype.Nb=function(a,b){return r(this,a,!0,b)},e.prototype.Ob=function(a,b){return s(this,a,!1,b)},e.prototype.Pb=function(a,b){return s(this,a,!0,b)},e.prototype.Qb=function(a,b){return t(this,a,!1,b)},e.prototype.Rb=function(a,b){return t(this,a,!0,b)},e.prototype.Sb=function(a,b){return u(this,a,!1,b)},e.prototype.Tb=function(a,b){return u(this,a,!0,b)},e.prototype.Ub=function(a,b,c){var d=this;c||(E.ok(void 0!==a&&null!==a,"missing value"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b<d.length,"trying to write beyond buffer length"),v(a,255)),b<d.length&&(d[b]=a)},e.prototype.Vb=function(a,b,c){w(this,a,b,!1,c)},e.prototype.Wb=function(a,b,c){w(this,a,b,!0,c)},e.prototype.Xb=function(a,b,c){x(this,a,b,!1,c)},e.prototype.Yb=function(a,b,c){x(this,a,b,!0,c)},e.prototype.Zb=function(a,b,c){var d=this;c||(E.ok(void 0!==a&&null!==a,"missing value"),E.ok(void 0!==b&&null!==b,"missing offset"),E.ok(b<d.length,"Trying to write beyond buffer length"),y(a,127,-128)),a>=0?d.Ub(a,b,c):d.Ub(255+a+1,b,c)},e.prototype.$b=function(a,b,c){A(this,a,b,!1,c)},e.prototype._b=function(a,b,c){A(this,a,b,!0,c)},e.prototype.ac=function(a,b,c){B(this,a,b,!1,c)},e.prototype.bc=function(a,b,c){B(this,a,b,!0,c)},e.prototype.cc=function(a,b,c){C(this,a,b,!1,c)},e.prototype.dc=function(a,b,c){C(this,a,b,!0,c)},e.prototype.ec=function(a,b,c){D(this,a,b,!1,c)},e.prototype.fc=function(a,b,c){D(this,a,b,!0,c)}},{gc:1,assert:6,hc:4}],jc:[function(a,b){b.g=a("q9TxCC")},{}],4:[function(a,b){!function(){"use strict";function a(a){var b,c,e,f,g,h;if(a.length%4>0)throw"Invalid string. Length must be a multiple of 4";for(g=a.indexOf("="),g=g>0?a.length-g:0,h=[],e=g>0?a.length-4:a.length,b=0,c=0;e>b;b+=4,c+=3)f=d.indexOf(a[b])<<18|d.indexOf(a[b+1])<<12|d.indexOf(a[b+2])<<6|d.indexOf(a[b+3]),h.push((16711680&f)>>16),h.push((65280&f)>>8),h.push(255&f);return 2===g?(f=d.indexOf(a[b])<<2|d.indexOf(a[b+1])>>4,h.push(255&f)):1===g&&(f=d.indexOf(a[b])<<10|d.indexOf(a[b+1])<<4|d.indexOf(a[b+2])>>2,h.push(f>>8&255),h.push(255&f)),h}function c(a){function b(a){return d[a>>18&63]+d[a>>12&63]+d[a>>6&63]+d[63&a]}var c,e,f,g=a.length%3,h="";for(c=0,f=a.length-g;f>c;c+=3)e=(a[c]<<16)+(a[c+1]<<8)+a[c+2],h+=b(e);switch(g){case 1:e=a[a.length-1],h+=d[e>>2],h+=d[e<<4&63],h+="==";break;case 2:e=(a[a.length-2]<<8)+a[a.length-1],h+=d[e>>10],h+=d[e>>4&63],h+=d[e<<2&63],h+="="}return h}var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";b.g.l=a,b.g.m=c}()},{}],5:[function(a,b,c){function d(a){return"[object Array]"===j.call(a)}function e(a,b){var c;if(null===a)c={__proto__:null};else{if("object"!=typeof a)throw new TypeError("typeof prototype["+typeof a+"] != 'object'");var d=function(){};d.prototype=a,c=new d,c.__proto__=a}return void 0!==b&&Object.defineProperties&&Object.defineProperties(c,b),c}function f(a){return"object"!=typeof a&&"function"!=typeof a||null===a}function g(a){if(f(a))throw new TypeError("Object.keys called on a non-object");var b=[];for(var c in a)k.call(a,c)&&b.push(c);return b}function h(a){if(f(a))throw new TypeError("Object.getOwnPropertyNames called on a non-object");var b=g(a);return c.isArray(a)&&-1===c.indexOf(a,"length")&&b.push("length"),b}function i(a,b){return{value:a[b]}}var j=Object.prototype.toString,k=Object.prototype.hasOwnProperty;c.isArray="function"==typeof Array.isArray?Array.isArray:d,c.indexOf=function(a,b){if(a.indexOf)return a.indexOf(b);for(var c=0;c<a.length;c++)if(b===a[c])return c;return-1},c.filter=function(a,b){if(a.filter)return a.filter(b);for(var c=[],d=0;d<a.length;d++)b(a[d],d,a)&&c.push(a[d]);return c},c.forEach=function(a,b,c){if(a.forEach)return a.forEach(b,c);for(var d=0;d<a.length;d++)b.call(c,a[d],d,a)},c.map=function(a,b){if(a.map)return a.map(b);for(var c=Array(a.length),d=0;d<a.length;d++)c[d]=b(a[d],d,a);return c},c.reduce=function(a,b,c){if(a.reduce)return a.reduce(b,c);var d,e=!1;2<arguments.length&&(d=c,e=!0);for(var f=0,g=a.length;g>f;++f)a.hasOwnProperty(f)&&(e?d=b(d,a[f],f,a):(d=a[f],e=!0));return d},"b"!=="ab".substr(-1)?c.substr=function(a,b,c){return 0>b&&(b=a.length+b),a.substr(b,c)}:c.substr=function(a,b,c){return a.substr(b,c)},c.trim=function(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")},c.bind=function(){var a=Array.prototype.slice.call(arguments),b=a.shift();if(b.bind)return b.bind.apply(b,a);var c=a.shift();return function(){b.apply(c,a.concat([Array.prototype.slice.call(arguments)]))}},c.create="function"==typeof Object.create?Object.create:e;var l="function"==typeof Object.keys?Object.keys:g,m="function"==typeof Object.getOwnPropertyNames?Object.getOwnPropertyNames:h;if(Error().hasOwnProperty("description")){var n=function(a,b){return"[object Error]"===j.call(a)&&(b=c.filter(b,function(a){return"description"!==a&&"number"!==a&&"message"!==a})),b};c.keys=function(a){return n(a,l(a))},c.getOwnPropertyNames=function(a){return n(a,m(a))}}else c.keys=l,c.getOwnPropertyNames=m;if("function"==typeof Object.getOwnPropertyDescriptor)try{Object.getOwnPropertyDescriptor({a:1},"a"),c.getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor}catch(a){c.getOwnPropertyDescriptor=function(a,b){try{return Object.getOwnPropertyDescriptor(a,b)}catch(c){return i(a,b)}}}else c.getOwnPropertyDescriptor=i},{}],6:[function(a,b){function c(a,b){return m.p(b)?""+b:!m.q(b)||!isNaN(b)&&isFinite(b)?m.s(b)||m.t(b)?""+b:b:""+b}function d(a,b){return m.u(a)?a.length<b?a:a.slice(0,b):a}function e(a){return d(JSON.stringify(a.v,c),128)+" "+a.operator+" "+d(JSON.stringify(a.A,c),128)}function f(a,b,c,d,e){throw new p.B({message:c,v:a,A:b,operator:d,C:e})}function g(a,b){a||f(a,!0,b,"==",p.ok)}function h(a,b){if(a===b)return!0;if(m.isBuffer(a)&&m.isBuffer(b)){if(a.length!=b.length)return!1;for(var c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}return m.D(a)&&m.D(b)?a.getTime()===b.getTime():m.t(a)&&m.t(b)?a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.lastIndex===b.lastIndex&&a.ignoreCase===b.ignoreCase:m.F(a)||m.F(b)?j(a,b):a==b}function i(a){return"[object Arguments]"==Object.prototype.toString.call(a)}function j(a,b){if(m.G(a)||m.G(b))return!1;if(a.prototype!==b.prototype)return!1;if(i(a))return i(b)?(a=o.call(a),b=o.call(b),h(a,b)):!1;try{var c,d,e=n.keys(a),f=n.keys(b)}catch(a){return!1}if(e.length!=f.length)return!1;for(e.sort(),f.sort(),d=e.length-1;d>=0;d--)if(e[d]!=f[d])return!1;for(d=e.length-1;d>=0;d--)if(c=e[d],!h(a[c],b[c]))return!1;return!0}function k(a,b){return a&&b?"[object RegExp]"==Object.prototype.toString.call(b)?b.test(a):a instanceof b?!0:b.call({},a)===!0:!1}function l(a,b,c,d){var e;m.u(c)&&(d=c,c=null);try{b()}catch(a){e=a}if(d=(c&&c.name?" ("+c.name+").":".")+(d?" "+d:"."),a&&!e&&f(e,c,"Missing expected exception"+d),!a&&k(e,c)&&f(e,c,"Got unwanted exception"+d),a&&e&&c&&!k(e,c)||!a&&e)throw e}var m=a("util"),n=a("_shims"),o=Array.prototype.slice,p=b.g=g;p.B=function(a){this.name="AssertionError",this.v=a.v,this.A=a.A,this.operator=a.operator,this.message=a.message||e(this)},m.H(p.B,Error),p.I=f,p.ok=g,p.J=function(a,b,c){a!=b&&f(a,b,c,"==",p.J)},p.K=function(a,b,c){a==b&&f(a,b,c,"!=",p.K)},p.L=function(a,b,c){h(a,b)||f(a,b,c,"deepEqual",p.L)},p.M=function(a,b,c){h(a,b)&&f(a,b,c,"notDeepEqual",p.M)},p.N=function(a,b,c){a!==b&&f(a,b,c,"===",p.N)},p.O=function(a,b,c){a===b&&f(a,b,c,"!==",p.O)},p.P=function(){l.apply(this,[!0].concat(o.call(arguments)))},p.R=function(){l.apply(this,[!1].concat(o.call(arguments)))},p.S=function(a){if(a)throw a}},{T:5,U:7}],7:[function(a,b,c){function d(a,b){var d={La:[],Ma:f};return arguments.length>=3&&(d.Na=arguments[2]),arguments.length>=4&&(d.Oa=arguments[3]),o(b)?d.Pa=b:b&&c.Qa(d,b),u(d.Pa)&&(d.Pa=!1),u(d.Na)&&(d.Na=2),u(d.Oa)&&(d.Oa=!1),u(d.Ra)&&(d.Ra=!0),d.Oa&&(d.Ma=e),h(d,a,d.Na)}function e(a,b){var c=d.Sa[b];return c?"["+d.Oa[c][0]+"m"+a+"["+d.Oa[c][1]+"m":a}function f(a){return a}function g(a){var b={};return G.forEach(a,function(a){b[a]=!0}),b}function h(a,b,d){if(a.Ra&&b&&z(b.Ta)&&b.Ta!==c.Ta&&(!b.constructor||b.constructor.prototype!==b)){var e=b.Ta(d);return s(e)||(e=h(a,e,d)),e}var f=i(a,b);if(f)return f;var o=G.keys(b),p=g(o);if(a.Pa&&(o=G.getOwnPropertyNames(b)),0===o.length){if(z(b)){var q=b.name?": "+b.name:"";return a.Ma("[Function"+q+"]","special")}if(v(b))return a.Ma(RegExp.prototype.toString.call(b),"regexp");if(x(b))return a.Ma(Date.prototype.toString.call(b),"date");if(y(b))return j(b)}var r="",t=!1,u=["{","}"];if(n(b)&&(t=!0,u=["[","]"]),z(b)){var w=b.name?": "+b.name:"";r=" [Function"+w+"]"}if(v(b)&&(r=" "+RegExp.prototype.toString.call(b)),x(b)&&(r=" "+Date.prototype.toUTCString.call(b)),y(b)&&(r=" "+j(b)),0===o.length&&(!t||0==b.length))return u[0]+r+u[1];if(0>d)return v(b)?a.Ma(RegExp.prototype.toString.call(b),"regexp"):a.Ma("[Object]","special");a.La.push(b);var A;return A=t?k(a,b,d,p,o):o.map(function(c){return l(a,b,d,p,c,t)}),a.La.pop(),m(A,r,u)}function i(a,b){if(u(b))return a.Ma("undefined","undefined");if(s(b)){var c="'"+JSON.stringify(b).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return a.Ma(c,"string")}return r(b)?a.Ma(""+b,"number"):o(b)?a.Ma(""+b,"boolean"):p(b)?a.Ma("null","null"):void 0}function j(a){return"["+Error.prototype.toString.call(a)+"]"}function k(a,b,c,d,e){for(var f=[],g=0,h=b.length;h>g;++g)F(b,g+"")?f.push(l(a,b,c,d,g+"",!0)):f.push("");return G.forEach(e,function(e){e.match(/^\d+$/)||f.push(l(a,b,c,d,e,!0))}),f}function l(a,b,c,d,e,f){var g,i,j;if(j=G.getOwnPropertyDescriptor(b,e)||{value:b[e]},j.get?i=j.set?a.Ma("[Getter/Setter]","special"):a.Ma("[Getter]","special"):j.set&&(i=a.Ma("[Setter]","special")),F(d,e)||(g="["+e+"]"),i||(G.indexOf(a.La,j.value)<0?(i=p(c)?h(a,j.value,null):h(a,j.value,c-1),i.indexOf("\n")>-1&&(i=f?i.split("\n").map(function(a){return" "+a}).join("\n").substr(2):"\n"+i.split("\n").map(function(a){return" "+a}).join("\n"))):i=a.Ma("[Circular]","special")),u(g)){if(f&&e.match(/^\d+$/))return i;g=JSON.stringify(""+e),g.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(g=g.substr(1,g.length-2),g=a.Ma(g,"name")):(g=g.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),g=a.Ma(g,"string"))}return g+": "+i}function m(a,b,c){var d=0,e=G.reduce(a,function(a,b){return d++,b.indexOf("\n")>=0&&d++,a+b.replace(/\u001b\[\d\d?m/g,"").length+1},0);return e>60?c[0]+(""===b?"":b+"\n ")+" "+a.join(",\n ")+" "+c[1]:c[0]+b+" "+a.join(", ")+" "+c[1]}function n(a){return G.isArray(a)}function o(a){return"boolean"==typeof a}function p(a){return null===a}function q(a){return null==a}function r(a){return"number"==typeof a}function s(a){return"string"==typeof a}function t(a){return"symbol"==typeof a}function u(a){return void 0===a}function v(a){return w(a)&&"[object RegExp]"===C(a)}function w(a){return"object"==typeof a&&a}function x(a){return w(a)&&"[object Date]"===C(a)}function y(a){return w(a)&&"[object Error]"===C(a)}function z(a){return"function"==typeof a}function A(a){return null===a||"boolean"==typeof a||"number"==typeof a||"string"==typeof a||"symbol"==typeof a||void 0===a}function B(a){return a instanceof Buffer}function C(a){return Object.prototype.toString.call(a)}function D(a){return 10>a?"0"+a.toString(10):a.toString(10)}function E(){var a=new Date,b=[D(a.getHours()),D(a.getMinutes()),D(a.getSeconds())].join(":");return[a.getDate(),I[a.getMonth()],b].join(" ")}function F(a,b){return Object.prototype.hasOwnProperty.call(a,b)}var G=a("_shims"),H=/%[sdj%]/g;c.format=function(a){if(!s(a)){for(var b=[],c=0;c<arguments.length;c++)b.push(d(arguments[c]));return b.join(" ")}for(var c=1,e=arguments,f=e.length,g=(a+"").replace(H,function(a){if("%%"===a)return"%";if(c>=f)return a;switch(a){case"%s":return e[c++]+"";case"%d":return+e[c++];case"%j":try{return JSON.stringify(e[c++])}catch(a){return"[Circular]"}default:return a}}),h=e[c];f>c;h=e[++c])g+=p(h)||!w(h)?" "+h:" "+d(h);return g},c.Ta=d,d.Oa={bold:[1,22],Wa:[3,23],Xa:[4,24],inverse:[7,27],Ya:[37,39],Za:[90,39],$a:[30,39],blue:[34,39],_a:[36,39],green:[32,39],ab:[35,39],red:[31,39],bb:[33,39]},d.Sa={cb:"cyan",number:"yellow",eb:"yellow",undefined:"grey",fb:"bold",gb:"green",hb:"magenta",ib:"red"},c.isArray=n,c.pa=o,c.qa=p,c.G=q,c.q=r,c.u=s,c.jb=t,c.p=u,c.t=v,c.F=w,c.D=x,c.kb=y,c.s=z,c.lb=A,c.isBuffer=B;var I=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];c.log=function(){console.log("%s - %s",E(),c.format.apply(c,arguments))},c.H=function(a,b){a.mb=b,a.prototype=G.create(b.prototype,{constructor:{value:a,nb:!1,ob:!0,pb:!0}})},c.Qa=function(a,b){if(!b||!w(b))return a;for(var c=G.keys(b),d=c.length;d--;)a[c[d]]=b[c[d]];return a}},{T:5}]},{},[]),b.g=a("buffer-browserify")},{}],15:[function(b,c,d){var e="undefined"!=typeof self?self:"undefined"!=typeof window?window:{};(function(){function b(a,b){if(a!==b){var c=null===a,d=a===A,e=a===a,f=null===b,g=b===A,h=b===b;if(a>b&&!f||!e||c&&!g&&h||d&&h)return 1;if(b>a&&!c||!h||f&&!d&&e||g&&e)return-1}return 0}function f(a,b,c){for(var d=a.length,e=c?d:-1;c?e--:++e<d;)if(b(a[e],e,a))return e;return-1}function g(a,b,c){if(b!==b)return r(a,c);for(var d=c-1,e=a.length;++d<e;)if(a[d]===b)return d;
return-1}function h(a){return"function"==typeof a||!1}function i(a){return null==a?"":a+""}function j(a,b){for(var c=-1,d=a.length;++c<d&&b.indexOf(a.charAt(c))>-1;);return c}function k(a,b){for(var c=a.length;c--&&b.indexOf(a.charAt(c))>-1;);return c}function l(a,c){return b(a.kc,c.kc)||a.index-c.index}function m(a,c,d){for(var e=-1,f=a.kc,g=c.kc,h=f.length,i=d.length;++e<h;){var j=b(f[e],g[e]);if(j){if(e>=i)return j;var k=d[e];return j*("asc"===k||k===!0?1:-1)}}return a.index-c.index}function n(a){return Ua[a]}function o(a){return Va[a]}function p(a,b,c){return b?a=Ya[a]:c&&(a=Za[a]),"\\"+a}function q(a){return"\\"+Za[a]}function r(a,b,c){for(var d=a.length,e=b+(c?0:-1);c?e--:++e<d;){var f=a[e];if(f!==f)return e}return-1}function s(a){return!!a&&"object"==typeof a}function t(a){return 160>=a&&a>=9&&13>=a||32==a||160==a||5760==a||6158==a||a>=8192&&(8202>=a||8232==a||8233==a||8239==a||8287==a||12288==a||65279==a)}function u(a,b){for(var c=-1,d=a.length,e=-1,f=[];++c<d;)a[c]===b&&(a[c]=T,f[++e]=c);return f}function v(a,b){for(var c,d=-1,e=a.length,f=-1,g=[];++d<e;){var h=a[d],i=b?b(h,d,a):h;d&&c===i||(c=i,g[++f]=h)}return g}function w(a){for(var b=-1,c=a.length;++b<c&&t(a.charCodeAt(b)););return b}function x(a){for(var b=a.length;b--&&t(a.charCodeAt(b)););return b}function y(a){return Wa[a]}function z(a){function c(a){if(s(a)&&!Ih(a)&&!(a instanceof t)){if(a instanceof e)return a;if(dg.call(a,"__chain__")&&dg.call(a,"__wrapped__"))return od(a)}return new e(a)}function d(){}function e(a,b,c){this.lc=a,this.mc=c||[],this.nc=!!b}function t(a){this.lc=a,this.mc=[],this.oc=1,this.pc=!1,this.qc=[],this.rc=Eg,this.sc=[]}function $(){var a=new t(this.lc);return a.mc=bb(this.mc),a.oc=this.oc,a.pc=this.pc,a.qc=bb(this.qc),a.rc=this.rc,a.sc=bb(this.sc),a}function ca(){if(this.pc){var a=new t(this);a.oc=-1,a.pc=!0}else a=this.clone(),a.oc*=-1;return a}function ea(){var a=this.lc.value(),b=this.oc,c=Ih(a),d=0>b,e=c?a.length:0,f=Vc(0,e,this.sc),g=f.start,h=f.end,i=h-g,j=d?h:g-1,k=this.qc,l=k.length,m=0,n=zg(i,this.rc);if(!c||P>e||e==i&&n==i)return ec(a,this.mc);var o=[];a:for(;i--&&n>m;){j+=b;for(var p=-1,q=a[j];++p<l;){var r=k[p],s=r.tc,t=r.type,u=s(q);if(t==R)q=u;else if(!u){if(t==Q)continue a;break a}}o[m++]=q}return o}function Ua(){this.uc={}}function Va(a){return this.has(a)&&delete this.uc[a]}function Wa(a){return"__proto__"==a?A:this.uc[a]}function Xa(a){return"__proto__"!=a&&dg.call(this.uc,a)}function Ya(a,b){return"__proto__"!=a&&(this.uc[a]=b),this}function Za(a){var b=a?a.length:0;for(this.data={hash:tg(null),set:new ng};b--;)this.push(a[b])}function $a(a,b){var c=a.data,d="string"==typeof b||Je(b)?c.set.has(b):c.hash[b];return d?0:-1}function _a(a){var b=this.data;"string"==typeof a||Je(a)?b.set.add(a):b.hash[a]=!0}function ab(a,b){for(var c=-1,d=a.length,e=-1,f=b.length,g=Qf(d+f);++c<d;)g[c]=a[c];for(;++e<f;)g[c++]=b[e];return g}function bb(a,b){var c=-1,d=a.length;for(b||(b=Qf(d));++c<d;)b[c]=a[c];return b}function cb(a,b){for(var c=-1,d=a.length;++c<d&&b(a[c],c,a)!==!1;);return a}function db(a,b){for(var c=a.length;c--&&b(a[c],c,a)!==!1;);return a}function hb(a,b){for(var c=-1,d=a.length;++c<d;)if(!b(a[c],c,a))return!1;return!0}function ib(a,b,c,d){for(var e=-1,f=a.length,g=d,h=g;++e<f;){var i=a[e],j=+b(i);c(j,g)&&(g=j,h=i)}return h}function jb(a,b){for(var c=-1,d=a.length,e=-1,f=[];++c<d;){var g=a[c];b(g,c,a)&&(f[++e]=g)}return f}function kb(a,b){for(var c=-1,d=a.length,e=Qf(d);++c<d;)e[c]=b(a[c],c,a);return e}function lb(a,b){for(var c=-1,d=b.length,e=a.length;++c<d;)a[e+c]=b[c];return a}function mb(a,b,c,d){var e=-1,f=a.length;for(d&&f&&(c=a[++e]);++e<f;)c=b(c,a[e],e,a);return c}function nb(a,b,c,d){var e=a.length;for(d&&e&&(c=a[--e]);e--;)c=b(c,a[e],e,a);return c}function ob(a,b){for(var c=-1,d=a.length;++c<d;)if(b(a[c],c,a))return!0;return!1}function pb(a,b){for(var c=a.length,d=0;c--;)d+=+b(a[c])||0;return d}function qb(a,b){return a===A?b:a}function rb(a,b,c,d){return a!==A&&dg.call(d,c)?a:b}function sb(a,b,c){for(var d=-1,e=Th(b),f=e.length;++d<f;){var g=e[d],h=a[g],i=c(h,b[g],g,a,b);(i===i?i===h:h!==h)&&(h!==A||g in a)||(a[g]=i)}return a}function tb(a,b){return null==b?a:vb(b,Th(b),a)}function ub(a,b){for(var c=-1,d=null==a,e=!d&&$c(a),f=e?a.length:0,g=b.length,h=Qf(g);++c<g;){var i=b[c];e?h[c]=_c(i,f)?a[i]:A:h[c]=d?A:a[i]}return h}function vb(a,b,c){c||(c={});for(var d=-1,e=b.length;++d<e;){var f=b[d];c[f]=a[f]}return c}function wb(a,b,c){var d=typeof a;return"function"==d?b===A?a:hc(a,b,c):null==a?Df:"object"==d?Pb(a):b===A?Jf(a):Qb(a,b)}function xb(a,b,c,d,e,f,g){var h;if(c&&(h=e?c(a,d,e):c(a)),h!==A)return h;if(!Je(a))return a;var i=Ih(a);if(i){if(h=Wc(a),!b)return bb(a,h)}else{var j=fg.call(a),k=j==Z;if(j!=aa&&j!=U&&(!k||e))return Ta[j]?Yc(a,j,b):e?a:{};if(fb(a))return e?a:{};if(h=Xc(k?{}:a),!b)return tb(h,a)}f||(f=[]),g||(g=[]);for(var l=f.length;l--;)if(f[l]==a)return g[l];return f.push(a),g.push(h),(i?cb:Hb)(a,function(d,e){h[e]=xb(d,b,c,e,a,f,g)}),h}function yb(a,b,c){if("function"!=typeof a)throw new Zf(S);return og(function(){a.apply(A,c)},b)}function zb(a,b){var c=a?a.length:0,d=[];if(!c)return d;var e=-1,f=Sc(),h=f===g,i=h&&b.length>=P?qc(b):null,j=b.length;i&&(f=$a,h=!1,b=i);a:for(;++e<c;){var k=a[e];if(h&&k===k){for(var l=j;l--;)if(b[l]===k)continue a;d.push(k)}else f(b,k,0)<0&&d.push(k)}return d}function Ab(a,b){var c=!0;return Pg(a,function(a,d,e){return c=!!b(a,d,e)}),c}function Bb(a,b,c,d){var e=d,f=e;return Pg(a,function(a,g,h){var i=+b(a,g,h);(c(i,e)||i===d&&i===f)&&(e=i,f=a)}),f}function Cb(a,b,c,d){var e=a.length;for(c=null==c?0:+c||0,0>c&&(c=-c>e?0:e+c),d=d===A||d>e?e:+d||0,0>d&&(d+=e),e=c>d?0:d>>>0,c>>>=0;e>c;)a[c++]=b;return a}function Db(a,b){var c=[];return Pg(a,function(a,d,e){b(a,d,e)&&c.push(a)}),c}function Eb(a,b,c,d){var e;return c(a,function(a,c,f){return b(a,c,f)?(e=d?c:a,!1):A}),e}function Fb(a,b,c,d){d||(d=[]);for(var e=-1,f=a.length;++e<f;){var g=a[e];s(g)&&$c(g)&&(c||Ih(g)||Ae(g))?b?Fb(g,b,c,d):lb(d,g):c||(d[d.length]=g)}return d}function Gb(a,b){return Rg(a,b,bf)}function Hb(a,b){return Rg(a,b,Th)}function Ib(a,b){return Sg(a,b,Th)}function Jb(a,b){for(var c=-1,d=b.length,e=-1,f=[];++c<d;){var g=b[c];Ie(a[g])&&(f[++e]=g)}return f}function Kb(a,b,c){if(null!=a){a=md(a),c!==A&&c in a&&(b=[c]);for(var d=0,e=b.length;null!=a&&e>d;)a=md(a)[b[d++]];return d&&d==e?a:A}}function Lb(a,b,c,d,e,f){return a===b?!0:null==a||null==b||!Je(a)&&!s(b)?a!==a&&b!==b:Mb(a,b,Lb,c,d,e,f)}function Mb(a,b,c,d,e,f,g){var h=Ih(a),i=Ih(b),j=V,k=V;h||(j=fg.call(a),j==U?j=aa:j!=aa&&(h=Se(a))),i||(k=fg.call(b),k==U?k=aa:k!=aa&&(i=Se(b)));var l=j==aa&&!fb(a),m=k==aa&&!fb(b),n=j==k;if(n&&!h&&!l)return Oc(a,b,j);if(!e){var o=l&&dg.call(a,"__wrapped__"),p=m&&dg.call(b,"__wrapped__");if(o||p)return c(o?a.value():a,p?b.value():b,d,e,f,g)}if(!n)return!1;f||(f=[]),g||(g=[]);for(var q=f.length;q--;)if(f[q]==a)return g[q]==b;f.push(a),g.push(b);var r=(h?Nc:Pc)(a,b,c,d,e,f,g);return f.pop(),g.pop(),r}function Nb(a,b,c){var d=b.length,e=d,f=!c;if(null==a)return!e;for(a=md(a);d--;){var g=b[d];if(f&&g[2]?g[1]!==a[g[0]]:!(g[0]in a))return!1}for(;++d<e;){g=b[d];var h=g[0],i=a[h],j=g[1];if(f&&g[2]){if(i===A&&!(h in a))return!1}else{var k=c?c(i,j,h):A;if(!(k===A?Lb(j,i,c,!0):k))return!1}}return!0}function Ob(a,b){var c=-1,d=$c(a)?Qf(a.length):[];return Pg(a,function(a,e,f){d[++c]=b(a,e,f)}),d}function Pb(a){var b=Tc(a);if(1==b.length&&b[0][2]){var c=b[0][0],d=b[0][1];return function(a){return null==a?!1:(a=md(a),a[c]===d&&(d!==A||c in a))}}return function(a){return Nb(a,b)}}function Qb(a,b){var c=Ih(a),d=bd(a)&&ed(b),e=a+"";return a=nd(a),function(f){if(null==f)return!1;var g=e;if(f=md(f),(c||!d)&&!(g in f)){if(f=1==a.length?f:Kb(f,Yb(a,0,-1)),null==f)return!1;g=Bd(a),f=md(f)}return f[g]===b?b!==A||g in f:Lb(b,f[g],A,!0)}}function Rb(a,b,c,d,e){if(!Je(a))return a;var f=$c(b)&&(Ih(b)||Se(b)),g=f?A:Th(b);return cb(g||b,function(h,i){if(g&&(i=h,h=b[i]),s(h))d||(d=[]),e||(e=[]),Sb(a,b,i,Rb,c,d,e);else{var j=a[i],k=c?c(j,h,i,a,b):A,l=k===A;l&&(k=h),k===A&&(!f||i in a)||!l&&(k===k?k===j:j!==j)||(a[i]=k)}}),a}function Sb(a,b,c,d,e,f,g){for(var h=f.length,i=b[c];h--;)if(f[h]==i)return a[c]=g[h],A;var j=a[c],k=e?e(j,i,c,a,b):A,l=k===A;l&&(k=i,$c(i)&&(Ih(i)||Se(i))?k=Ih(j)?j:$c(j)?bb(j):[]:Pe(i)||Ae(i)?k=Ae(j)?Xe(j):Pe(j)?j:{}:l=!1),f.push(i),g.push(k),l?a[c]=d(k,i,e,f,g):(k===k?k!==j:j===j)&&(a[c]=k)}function Tb(a){return function(b){return null==b?A:md(b)[a]}}function Ub(a){var b=a+"";return a=nd(a),function(c){return Kb(c,a,b)}}function Vb(a,b){for(var c=a?b.length:0;c--;){var d=b[c];if(d!=e&&_c(d)){var e=d;pg.call(a,d,1)}}return a}function Wb(a,b){return a+ug(Cg()*(b-a+1))}function Xb(a,b,c,d,e){return e(a,function(a,e,f){c=d?(d=!1,a):b(c,a,e,f)}),c}function Yb(a,b,c){var d=-1,e=a.length;b=null==b?0:+b||0,0>b&&(b=-b>e?0:e+b),c=c===A||c>e?e:+c||0,0>c&&(c+=e),e=b>c?0:c-b>>>0,b>>>=0;for(var f=Qf(e);++d<e;)f[d]=a[d+b];return f}function Zb(a,b){var c;return Pg(a,function(a,d,e){return c=b(a,d,e),!c}),!!c}function $b(a,b){var c=a.length;for(a.sort(b);c--;)a[c]=a[c].value;return a}function _b(a,b,c){var d=Qc(),e=-1;b=kb(b,function(a){return d(a)});var f=Ob(a,function(a){var c=kb(b,function(b){return b(a)});return{kc:c,index:++e,value:a}});return $b(f,function(a,b){return m(a,b,c)})}function ac(a,b){var c=0;return Pg(a,function(a,d,e){c+=+b(a,d,e)||0}),c}function bc(a,b){var c=-1,d=Sc(),e=a.length,f=d===g,h=f&&e>=P,i=h?qc():null,j=[];i?(d=$a,f=!1):(h=!1,i=b?[]:j);a:for(;++c<e;){var k=a[c],l=b?b(k,c,a):k;if(f&&k===k){for(var m=i.length;m--;)if(i[m]===l)continue a;b&&i.push(l),j.push(k)}else d(i,l,0)<0&&((b||h)&&i.push(l),j.push(k))}return j}function cc(a,b){for(var c=-1,d=b.length,e=Qf(d);++c<d;)e[c]=a[b[c]];return e}function dc(a,b,c,d){for(var e=a.length,f=d?e:-1;(d?f--:++f<e)&&b(a[f],f,a););return c?Yb(a,d?0:f,d?f+1:e):Yb(a,d?f+1:0,d?e:f)}function ec(a,b){var c=a;c instanceof t&&(c=c.value());for(var d=-1,e=b.length;++d<e;){var f=b[d];c=f.vc.apply(f.wc,lb([c],f.xc))}return c}function fc(a,b,c){var d=0,e=a?a.length:d;if("number"==typeof b&&b===b&&Hg>=e){for(;e>d;){var f=d+e>>>1,g=a[f];(c?b>=g:b>g)&&null!==g?d=f+1:e=f}return e}return gc(a,b,Df,c)}function gc(a,b,c,d){b=c(b);for(var e=0,f=a?a.length:0,g=b!==b,h=null===b,i=b===A;f>e;){var j=ug((e+f)/2),k=c(a[j]),l=k!==A,m=k===k;if(g)var n=m||d;else n=h?m&&l&&(d||null!=k):i?m&&(d||l):null==k?!1:d?b>=k:b>k;n?e=j+1:f=j}return zg(f,Gg)}function hc(a,b,c){if("function"!=typeof a)return Df;if(b===A)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 3:return function(c,d,e){return a.call(b,c,d,e)};case 4:return function(c,d,e,f){return a.call(b,c,d,e,f)};case 5:return function(c,d,e,f,g){return a.call(b,c,d,e,f,g)}}return function(){return a.apply(b,arguments)}}function ic(a){var b=new ig(a.byteLength),c=new qg(b);return c.set(new qg(a)),b}function jc(a,b,c){for(var d=c.length,e=-1,f=yg(a.length-d,0),g=-1,h=b.length,i=Qf(h+f);++g<h;)i[g]=b[g];for(;++e<d;)i[c[e]]=a[e];for(;f--;)i[g++]=a[e++];return i}function kc(a,b,c){for(var d=-1,e=c.length,f=-1,g=yg(a.length-e,0),h=-1,i=b.length,j=Qf(g+i);++f<g;)j[f]=a[f];for(var k=f;++h<i;)j[k+h]=b[h];for(;++d<e;)j[k+c[d]]=a[f++];return j}function lc(a,b){return function(c,d,e){var f=b?b():{};if(d=Qc(d,e,3),Ih(c))for(var g=-1,h=c.length;++g<h;){var i=c[g];a(f,i,d(i,g,c),c)}else Pg(c,function(b,c,e){a(f,b,d(b,c,e),e)});return f}}function mc(a){return se(function(b,c){var d=-1,e=null==b?0:c.length,f=e>2?c[e-2]:A,g=e>2?c[2]:A,h=e>1?c[e-1]:A;for("function"==typeof f?(f=hc(f,h,5),e-=2):(f="function"==typeof h?h:A,e-=f?1:0),g&&ad(c[0],c[1],g)&&(f=3>e?A:f,e=1);++d<e;){var i=c[d];i&&a(b,i,f)}return b})}function nc(a,b){return function(c,d){var e=c?Vg(c):0;if(!dd(e))return a(c,d);for(var f=b?e:-1,g=md(c);(b?f--:++f<e)&&d(g[f],f,g)!==!1;);return c}}function oc(a){return function(b,c,d){for(var e=md(b),f=d(b),g=f.length,h=a?g:-1;a?h--:++h<g;){var i=f[h];if(c(e[i],i,e)===!1)break}return b}}function pc(a,b){function c(){var e=this&&this!==eb&&this instanceof c?d:a;return e.apply(b,arguments)}var d=sc(a);return c}function qc(a){return tg&&ng?new Za(a):null}function rc(a){return function(b){for(var c=-1,d=Af(mf(b)),e=d.length,f="";++c<e;)f=a(f,d[c],c);return f}}function sc(a){return function(){var b=arguments;switch(b.length){case 0:return new a;case 1:return new a(b[0]);case 2:return new a(b[0],b[1]);case 3:return new a(b[0],b[1],b[2]);case 4:return new a(b[0],b[1],b[2],b[3]);case 5:return new a(b[0],b[1],b[2],b[3],b[4]);case 6:return new a(b[0],b[1],b[2],b[3],b[4],b[5]);case 7:return new a(b[0],b[1],b[2],b[3],b[4],b[5],b[6])}var c=Og(a.prototype),d=a.apply(c,b);return Je(d)?d:c}}function tc(a){function b(c,d,e){e&&ad(c,d,e)&&(d=A);var f=Mc(c,a,A,A,A,A,A,d);return f.placeholder=b.placeholder,f}return b}function uc(a,b){return se(function(c){var d=c[0];return null==d?d:(c.push(b),a.apply(A,c))})}function vc(a,b){return function(c,d,e){if(e&&ad(c,d,e)&&(d=A),d=Qc(d,e,3),1==d.length){c=Ih(c)?c:ld(c);var f=ib(c,d,a,b);if(!c.length||f!==b)return f}return Bb(c,d,a,b)}}function wc(a,b){return function(c,d,e){if(d=Qc(d,e,3),Ih(c)){var g=f(c,d,b);return g>-1?c[g]:A}return Eb(c,d,a)}}function xc(a){return function(b,c,d){return b&&b.length?(c=Qc(c,d,3),f(b,c,a)):-1}}function yc(a){return function(b,c,d){return c=Qc(c,d,3),Eb(b,c,a,!0)}}function zc(a){return function(){for(var b,c=arguments.length,d=a?c:-1,f=0,g=Qf(c);a?d--:++d<c;){var h=g[f++]=arguments[d];if("function"!=typeof h)throw new Zf(S);!b&&e.prototype.yc&&"wrapper"==Rc(h)&&(b=new e([],!0))}for(d=b?-1:c;++d<c;){h=g[d];var i=Rc(h),j="wrapper"==i?Ug(h):A;b=j&&cd(j[0])&&j[1]==(J|F|H|K)&&!j[4].length&&1==j[9]?b[Rc(j[0])].apply(b,j[3]):1==h.length&&cd(h)?b[i]():b.yc(h)}return function(){var a=arguments,d=a[0];if(b&&1==a.length&&Ih(d)&&d.length>=P)return b.zc(d).value();for(var e=0,f=c?g[e].apply(this,a):d;++e<c;)f=g[e].call(this,f);return f}}}function Ac(a,b){return function(c,d,e){return"function"==typeof d&&e===A&&Ih(c)?a(c,d):b(c,hc(d,e,3))}}function Bc(a){return function(b,c,d){return"function"==typeof c&&d===A||(c=hc(c,d,3)),a(b,c,bf)}}function Cc(a){return function(b,c,d){return"function"==typeof c&&d===A||(c=hc(c,d,3)),a(b,c)}}function Dc(a){return function(b,c,d){var e={};return c=Qc(c,d,3),Hb(b,function(b,d,f){var g=c(b,d,f);d=a?g:d,b=a?b:g,e[d]=b}),e}}function Ec(a){return function(b,c,d){return b=i(b),(a?b:"")+Ic(b,c,d)+(a?"":b)}}function Fc(a){var b=se(function(c,d){var e=u(d,b.placeholder);return Mc(c,a,A,d,e)});return b}function Gc(a,b){return function(c,d,e,f){var g=arguments.length<3;return"function"==typeof d&&f===A&&Ih(c)?a(c,d,e,g):Xb(c,Qc(d,f,4),e,g,b)}}function Hc(a,b,c,d,e,f,g,h,i,j){function k(){for(var s=arguments.length,t=s,v=Qf(s);t--;)v[t]=arguments[t];if(d&&(v=jc(v,d,e)),f&&(v=kc(v,f,g)),o||q){var w=k.placeholder,x=u(v,w);if(s-=x.length,j>s){var y=h?bb(h):A,z=yg(j-s,0),B=o?x:A,E=o?A:x,F=o?v:A,G=o?A:v;b|=o?H:I,b&=~(o?I:H),p||(b&=~(C|D));var J=[a,b,c,F,B,G,E,y,i,z],K=Hc.apply(A,J);return cd(a)&&Wg(K,J),K.placeholder=w,K}}var L=m?c:this,M=n?L[a]:a;return h&&(v=jd(v,h)),l&&i<v.length&&(v.length=i),this&&this!==eb&&this instanceof k&&(M=r||sc(a)),M.apply(L,v)}var l=b&J,m=b&C,n=b&D,o=b&F,p=b&E,q=b&G,r=n?A:sc(a);return k}function Ic(a,b,c){var d=a.length;if(b=+b,d>=b||!wg(b))return"";var e=b-d;return c=null==c?" ":c+"",sf(c,sg(e/c.length)).slice(0,e)}function Jc(a,b,c,d){function e(){for(var b=-1,h=arguments.length,i=-1,j=d.length,k=Qf(j+h);++i<j;)k[i]=d[i];for(;h--;)k[i++]=arguments[++b];var l=this&&this!==eb&&this instanceof e?g:a;return l.apply(f?c:this,k)}var f=b&C,g=sc(a);return e}function Kc(a){var b=Uf[a];return function(a,c){return c=c===A?0:+c||0,c?(c=lg(10,c),b(a*c)/c):b(a)}}function Lc(a){return function(b,c,d,e){var f=Qc(d);return null==d&&f===wb?fc(b,c,a):gc(b,c,f(d,e,1),a)}}function Mc(a,b,c,d,e,f,g,h){var i=b&D;if(!i&&"function"!=typeof a)throw new Zf(S);var j=d?d.length:0;if(j||(b&=~(H|I),d=e=A),j-=e?e.length:0,b&I){var k=d,l=e;d=e=A}var m=i?A:Ug(a),n=[a,b,c,d,e,k,l,f,g,h];if(m&&(fd(n,m),b=n[1],h=n[9]),n[9]=null==h?i?0:a.length:yg(h-j,0)||0,b==C)var o=pc(n[0],n[2]);else o=b!=H&&b!=(C|H)||n[4].length?Hc.apply(A,n):Jc.apply(A,n);var p=m?Tg:Wg;return p(o,n)}function Nc(a,b,c,d,e,f,g){var h=-1,i=a.length,j=b.length;if(i!=j&&!(e&&j>i))return!1;for(;++h<i;){var k=a[h],l=b[h],m=d?d(e?l:k,e?k:l,h):A;if(m!==A){if(m)continue;return!1}if(e){if(!ob(b,function(a){return k===a||c(k,a,d,e,f,g)}))return!1}else if(k!==l&&!c(k,l,d,e,f,g))return!1}return!0}function Oc(a,b,c){switch(c){case W:case X:return+a==+b;case Y:return a.name==b.name&&a.message==b.message;case _:return a!=+a?b!=+b:a==+b;case ba:case da:return a==b+""}return!1}function Pc(a,b,c,d,e,f,g){var h=Th(a),i=h.length,j=Th(b),k=j.length;if(i!=k&&!e)return!1;for(var l=i;l--;){var m=h[l];if(!(e?m in b:dg.call(b,m)))return!1}for(var n=e;++l<i;){m=h[l];var o=a[m],p=b[m],q=d?d(e?p:o,e?o:p,m):A;if(!(q===A?c(o,p,d,e,f,g):q))return!1;n||(n="constructor"==m)}if(!n){var r=a.constructor,s=b.constructor;if(r!=s&&"constructor"in a&&"constructor"in b&&!("function"==typeof r&&r instanceof r&&"function"==typeof s&&s instanceof s))return!1}return!0}function Qc(a,b,d){var e=c.Ac||Bf;return e=e===Bf?wb:e,d?e(a,b,d):e}function Rc(a){for(var b=a.name+"",c=Kg[b],d=c?c.length:0;d--;){var e=c[d],f=e.vc;if(null==f||f==a)return e.name}return b}function Sc(a,b,d){var e=c.indexOf||zd;return e=e===zd?g:e,a?e(a,b,d):e}function Tc(a){for(var b=cf(a),c=b.length;c--;)b[c][2]=ed(b[c][1]);return b}function Uc(a,b){var c=null==a?A:a[b];return Me(c)?c:A}function Vc(a,b,c){for(var d=-1,e=c.length;++d<e;){var f=c[d],g=f.size;switch(f.type){case"drop":a+=g;break;case"dropRight":b-=g;break;case"take":b=zg(b,a+g);break;case"takeRight":a=yg(a,b-g)}}return{start:a,end:b}}function Wc(a){var b=a.length,c=new a.constructor(b);return b&&"string"==typeof a[0]&&dg.call(a,"index")&&(c.index=a.index,c.input=a.input),c}function Xc(a){var b=a.constructor;return"function"==typeof b&&b instanceof b||(b=Wf),new b}function Yc(a,b,c){var d=a.constructor;switch(b){case fa:return ic(a);case W:case X:return new d(+a);case ga:case ha:case ia:case ja:case ka:case la:case ma:case na:case oa:d instanceof d&&(d=Lg[b]);var e=a.buffer;return new d(c?ic(e):e,a.byteOffset,a.length);case _:case da:return new d(a);case ba:var f=new d(a.source,Ha.exec(a));f.lastIndex=a.lastIndex}return f}function Zc(a,b,c){null==a||bd(b,a)||(b=nd(b),a=1==b.length?a:Kb(a,Yb(b,0,-1)),b=Bd(b));var d=null==a?a:a[b];return null==d?A:d.apply(a,c)}function $c(a){return null!=a&&dd(Vg(a))}function _c(a,b){return a="number"==typeof a||Ka.test(a)?+a:-1,b=null==b?Ig:b,a>-1&&a%1==0&&b>a}function ad(a,b,c){if(!Je(c))return!1;var d=typeof b;if("number"==d?$c(c)&&_c(b,c.length):"string"==d&&b in c){var e=c[b];return a===a?a===e:e!==e}return!1}function bd(a,b){var c=typeof a;if("string"==c&&Aa.test(a)||"number"==c)return!0;if(Ih(a))return!1;var d=!za.test(a);return d||null!=b&&a in md(b)}function cd(a){var b=Rc(a),d=c[b];if("function"!=typeof d||!(b in t.prototype))return!1;if(a===d)return!0;var e=Ug(d);return!!e&&a===e[0]}function dd(a){return"number"==typeof a&&a>-1&&a%1==0&&Ig>=a}function ed(a){return a===a&&!Je(a)}function fd(a,b){var c=a[1],d=b[1],e=c|d,f=J>e,g=d==J&&c==F||d==J&&c==K&&a[7].length<=b[8]||d==(J|K)&&c==F;if(!f&&!g)return a;d&C&&(a[2]=b[2],e|=c&C?0:E);var h=b[3];if(h){var i=a[3];a[3]=i?jc(i,h,b[4]):bb(h),a[4]=i?u(a[3],T):bb(b[4])}return h=b[5],h&&(i=a[5],a[5]=i?kc(i,h,b[6]):bb(h),a[6]=i?u(a[5],T):bb(b[6])),h=b[7],h&&(a[7]=bb(h)),d&J&&(a[8]=null==a[8]?b[8]:zg(a[8],b[8])),null==a[9]&&(a[9]=b[9]),a[0]=b[0],a[1]=e,a}function gd(a,b){return a===A?b:Jh(a,b,gd)}function hd(a,b){a=md(a);for(var c=-1,d=b.length,e={};++c<d;){var f=b[c];f in a&&(e[f]=a[f])}return e}function id(a,b){var c={};return Gb(a,function(a,d,e){b(a,d,e)&&(c[d]=a)}),c}function jd(a,b){for(var c=a.length,d=zg(b.length,c),e=bb(a);d--;){var f=b[d];a[d]=_c(f,c)?e[f]:A}return a}function kd(a){for(var b=bf(a),c=b.length,d=c&&a.length,e=!!d&&dd(d)&&(Ih(a)||Ae(a)||Re(a)),f=-1,g=[];++f<c;){var h=b[f];(e&&_c(h,d)||dg.call(a,h))&&g.push(h)}return g}function ld(a){return null==a?[]:$c(a)?c.Cc.Bc&&Re(a)?a.split(""):Je(a)?a:Wf(a):gf(a)}function md(a){if(c.Cc.Bc&&Re(a)){for(var b=-1,d=a.length,e=Wf(a);++b<d;)e[b]=a.charAt(b);return e}return Je(a)?a:Wf(a)}function nd(a){if(Ih(a))return a;var b=[];return i(a).replace(Ba,function(a,c,d,e){b.push(d?e.replace(Fa,"$1"):c||a)}),b}function od(a){return a instanceof t?a.clone():new e(a.lc,a.nc,bb(a.mc))}function pd(a,b,c){b=(c?ad(a,b,c):null==b)?1:yg(ug(b)||1,1);for(var d=0,e=a?a.length:0,f=-1,g=Qf(sg(e/b));e>d;)g[++f]=Yb(a,d,d+=b);return g}function qd(a){for(var b=-1,c=a?a.length:0,d=-1,e=[];++b<c;){var f=a[b];f&&(e[++d]=f)}return e}function rd(a,b,c){var d=a?a.length:0;return d?((c?ad(a,b,c):null==b)&&(b=1),Yb(a,0>b?0:b)):[]}function sd(a,b,c){var d=a?a.length:0;return d?((c?ad(a,b,c):null==b)&&(b=1),b=d-(+b||0),Yb(a,0,0>b?0:b)):[]}function td(a,b,c){return a&&a.length?dc(a,Qc(b,c,3),!0,!0):[]}function ud(a,b,c){return a&&a.length?dc(a,Qc(b,c,3),!0):[]}function vd(a,b,c,d){var e=a?a.length:0;return e?(c&&"number"!=typeof c&&ad(a,b,c)&&(c=0,d=e),Cb(a,b,c,d)):[]}function wd(a){return a?a[0]:A}function xd(a,b,c){var d=a?a.length:0;return c&&ad(a,b,c)&&(b=!1),d?Fb(a,b):[]}function yd(a){var b=a?a.length:0;return b?Fb(a,!0):[]}function zd(a,b,c){var d=a?a.length:0;if(!d)return-1;if("number"==typeof c)c=0>c?yg(d+c,0):c;else if(c){var e=fc(a,b);return d>e&&(b===b?b===a[e]:a[e]!==a[e])?e:-1}return g(a,b,c||0)}function Ad(a){return sd(a,1)}function Bd(a){var b=a?a.length:0;return b?a[b-1]:A}function Cd(a,b,c){var d=a?a.length:0;if(!d)return-1;var e=d;if("number"==typeof c)e=(0>c?yg(d+c,0):zg(c||0,d-1))+1;else if(c){e=fc(a,b,!0)-1;var f=a[e];return(b===b?b===f:f!==f)?e:-1}if(b!==b)return r(a,e,!0);for(;e--;)if(a[e]===b)return e;return-1}function Dd(){var a=arguments,b=a[0];if(!b||!b.length)return b;for(var c=0,d=Sc(),e=a.length;++c<e;)for(var f=0,g=a[c];(f=d(b,g,f))>-1;)pg.call(b,f,1);return b}function Ed(a,b,c){var d=[];if(!a||!a.length)return d;var e=-1,f=[],g=a.length;for(b=Qc(b,c,3);++e<g;){var h=a[e];b(h,e,a)&&(d.push(h),f.push(e))}return Vb(a,f),d}function Fd(a){return rd(a,1)}function Gd(a,b,c){var d=a?a.length:0;return d?(c&&"number"!=typeof c&&ad(a,b,c)&&(b=0,c=d),Yb(a,b,c)):[]}function Hd(a,b,c){var d=a?a.length:0;return d?((c?ad(a,b,c):null==b)&&(b=1),Yb(a,0,0>b?0:b)):[]}function Id(a,b,c){var d=a?a.length:0;return d?((c?ad(a,b,c):null==b)&&(b=1),b=d-(+b||0),Yb(a,0>b?0:b)):[]}function Jd(a,b,c){return a&&a.length?dc(a,Qc(b,c,3),!1,!0):[]}function Kd(a,b,c){return a&&a.length?dc(a,Qc(b,c,3)):[]}function Ld(a,b,c,d){var e=a?a.length:0;if(!e)return[];null!=b&&"boolean"!=typeof b&&(d=c,c=ad(a,b,d)?A:b,b=!1);var f=Qc();return null==c&&f===wb||(c=f(c,d,3)),b&&Sc()===g?v(a,c):bc(a,c)}function Md(a){if(!a||!a.length)return[];var b=-1,c=0;a=jb(a,function(a){return $c(a)?(c=yg(a.length,c),!0):A});for(var d=Qf(c);++b<c;)d[b]=kb(a,Tb(b));return d}function Nd(a,b,c){var d=a?a.length:0;if(!d)return[];var e=Md(a);return null==b?e:(b=hc(b,c,4),kb(e,function(a){return mb(a,b,A,!0)}))}function Od(){for(var a=-1,b=arguments.length;++a<b;){var c=arguments[a];if($c(c))var d=d?lb(zb(d,c),zb(c,d)):c}return d?bc(d):[]}function Pd(a,b){var c=-1,d=a?a.length:0,e={};for(!d||b||Ih(a[0])||(b=[]);++c<d;){var f=a[c];b?e[f]=b[c]:f&&(e[f[0]]=f[1])}return e}function Qd(a){var b=c(a);return b.nc=!0,b}function Rd(a,b,c){return b.call(c,a),a}function Sd(a,b,c){return b.call(c,a)}function Td(){return Qd(this)}function Ud(){return new e(this.value(),this.nc)}function Vd(a){for(var b,c=this;c instanceof d;){var e=od(c);b?f.lc=e:b=e;var f=e;c=c.lc}return f.lc=a,b}function Wd(){var a=this.lc,b=function(a){return a.reverse()};if(a instanceof t){var c=a;return this.mc.length&&(c=new t(this)),c=c.reverse(),c.mc.push({vc:Sd,xc:[b],wc:A}),new e(c,this.nc)}return this.yc(b)}function Xd(){return this.value()+""}function Yd(){return ec(this.lc,this.mc)}function Zd(a,b,c){var d=Ih(a)?hb:Ab;return c&&ad(a,b,c)&&(b=A),"function"==typeof b&&c===A||(b=Qc(b,c,3)),d(a,b)}function $d(a,b,c){var d=Ih(a)?jb:Db;return b=Qc(b,c,3),d(a,b)}function _d(a,b){return jh(a,Pb(b))}function ae(a,b,c,d){var e=a?Vg(a):0;return dd(e)||(a=gf(a),e=a.length),c="number"!=typeof c||d&&ad(b,c,d)?0:0>c?yg(e+c,0):c||0,"string"==typeof a||!Ih(a)&&Re(a)?e>=c&&a.indexOf(b,c)>-1:!!e&&Sc(a,b,c)>-1}function be(a,b,c){var d=Ih(a)?kb:Ob;return b=Qc(b,c,3),d(a,b)}function ce(a,b){return be(a,Jf(b))}function de(a,b,c){var d=Ih(a)?jb:Db;return b=Qc(b,c,3),d(a,function(a,c,d){return!b(a,c,d)})}function ee(a,b,c){if(c?ad(a,b,c):null==b){a=ld(a);var d=a.length;return d>0?a[Wb(0,d-1)]:A}var e=-1,f=We(a),d=f.length,g=d-1;for(b=zg(0>b?0:+b||0,d);++e<b;){var h=Wb(e,g),i=f[h];f[h]=f[e],f[e]=i}return f.length=b,f}function fe(a){return ee(a,Eg)}function ge(a){var b=a?Vg(a):0;return dd(b)?b:Th(a).length}function he(a,b,c){var d=Ih(a)?ob:Zb;return c&&ad(a,b,c)&&(b=A),"function"==typeof b&&c===A||(b=Qc(b,c,3)),d(a,b)}function ie(a,b,c){if(null==a)return[];c&&ad(a,b,c)&&(b=A);var d=-1;b=Qc(b,c,3);var e=Ob(a,function(a,c,e){return{kc:b(a,c,e),index:++d,value:a}});return $b(e,l)}function je(a,b,c,d){return null==a?[]:(d&&ad(b,c,d)&&(c=A),Ih(b)||(b=null==b?[]:[b]),Ih(c)||(c=null==c?[]:[c]),_b(a,b,c))}function ke(a,b){return $d(a,Pb(b))}function le(a,b){if("function"!=typeof b){if("function"!=typeof a)throw new Zf(S);var c=a;a=b,b=c}return a=wg(a=+a)?a:0,function(){return--a<1?b.apply(this,arguments):A}}function me(a,b,c){return c&&ad(a,b,c)&&(b=A),b=a&&null==b?a.length:yg(+b||0,0),Mc(a,J,A,A,A,A,b)}function ne(a,b){var c;if("function"!=typeof b){if("function"!=typeof a)throw new Zf(S);var d=a;a=b,b=d}return function(){return--a>0&&(c=b.apply(this,arguments)),1>=a&&(b=A),c}}function oe(a,b,c){function d(){n&&jg(n),j&&jg(j),p=0,j=n=o=A}function e(b,c){c&&jg(c),j=n=o=A,b&&(p=uh(),k=a.apply(m,i),n||j||(i=m=A))}function f(){var a=b-(uh()-l);0>=a||a>b?e(o,j):n=og(f,a)}function g(){e(r,n)}function h(){if(i=arguments,l=uh(),m=this,o=r&&(n||!s),q===!1)var c=s&&!n;else{j||s||(p=l);var d=q-(l-p),e=0>=d||d>q;e?(j&&(j=jg(j)),p=l,k=a.apply(m,i)):j||(j=og(g,d))}return e&&n?n=jg(n):n||b===q||(n=og(f,b)),c&&(e=!0,k=a.apply(m,i)),!e||n||j||(i=m=A),k}var i,j,k,l,m,n,o,p=0,q=!1,r=!0;if("function"!=typeof a)throw new Zf(S);if(b=0>b?0:+b||0,c===!0){var s=!0;r=!1}else Je(c)&&(s=!!c.Dc,q="maxWait"in c&&yg(+c.Ec||0,b),r="trailing"in c?!!c.Fc:r);return h.cancel=d,h}function pe(a,b){if("function"!=typeof a||b&&"function"!=typeof b)throw new Zf(S);var c=function(){var d=arguments,e=b?b.apply(this,d):d[0],f=c.Gc;if(f.has(e))return f.get(e);var g=a.apply(this,d);return c.Gc=f.set(e,g),g};return c.Gc=new pe.Hc,c}function qe(a){if("function"!=typeof a)throw new Zf(S);return function(){return!a.apply(this,arguments)}}function re(a){return ne(2,a)}function se(a,b){if("function"!=typeof a)throw new Zf(S);return b=yg(b===A?a.length-1:+b||0,0),function(){for(var c=arguments,d=-1,e=yg(c.length-b,0),f=Qf(e);++d<e;)f[d]=c[b+d];switch(b){case 0:return a.call(this,f);case 1:return a.call(this,c[0],f);case 2:return a.call(this,c[0],c[1],f)}var g=Qf(b+1);for(d=-1;++d<b;)g[d]=c[d];return g[b]=f,a.apply(this,g)}}function te(a){if("function"!=typeof a)throw new Zf(S);return function(b){return a.apply(this,b)}}function ue(a,b,c){var d=!0,e=!0;if("function"!=typeof a)throw new Zf(S);return c===!1?d=!1:Je(c)&&(d="leading"in c?!!c.Dc:d,e="trailing"in c?!!c.Fc:e),oe(a,b,{Dc:d,Ec:+b,Fc:e})}function ve(a,b){return b=null==b?Df:b,Mc(b,H,A,[a],[])}function we(a,b,c,d){return b&&"boolean"!=typeof b&&ad(a,b,c)?b=!1:"function"==typeof b&&(d=c,c=b,b=!1),"function"==typeof c?xb(a,b,hc(c,d,3)):xb(a,b)}function xe(a,b,c){return"function"==typeof b?xb(a,!0,hc(b,c,3)):xb(a,!0)}function ye(a,b){return a>b}function ze(a,b){return a>=b}function Ae(a){return s(a)&&$c(a)&&dg.call(a,"callee")&&!mg.call(a,"callee")}function Be(a){return a===!0||a===!1||s(a)&&fg.call(a)==W}function Ce(a){return s(a)&&fg.call(a)==X}function De(a){return!!a&&1===a.nodeType&&s(a)&&!Pe(a)}function Ee(a){return null==a?!0:$c(a)&&(Ih(a)||Re(a)||Ae(a)||s(a)&&Ie(a.splice))?!a.length:!Th(a).length}function Fe(a,b,c,d){c="function"==typeof c?hc(c,d,3):A;var e=c?c(a,b):A;return e===A?Lb(a,b,c):!!e}function Ge(a){return s(a)&&"string"==typeof a.message&&fg.call(a)==Y}function He(a){return"number"==typeof a&&wg(a)}function Ie(a){return Je(a)&&fg.call(a)==Z}function Je(a){var b=typeof a;return!!a&&("object"==b||"function"==b)}function Ke(a,b,c,d){return c="function"==typeof c?hc(c,d,3):A,Nb(a,Tc(b),c)}function Le(a){return Oe(a)&&a!=+a}function Me(a){return null==a?!1:Ie(a)?hg.test(cg.call(a)):s(a)&&(fb(a)?hg:Ja).test(a)}function Ne(a){return null===a}function Oe(a){return"number"==typeof a||s(a)&&fg.call(a)==_}function Pe(a){var b;if(!s(a)||fg.call(a)!=aa||fb(a)||Ae(a)||!dg.call(a,"constructor")&&(b=a.constructor,"function"==typeof b&&!(b instanceof b)))return!1;var d;return c.Cc.Ic?(Gb(a,function(a,b,c){return d=dg.call(c,b),!1}),d!==!1):(Gb(a,function(a,b){d=b}),d===A||dg.call(a,d))}function Qe(a){return Je(a)&&fg.call(a)==ba}function Re(a){return"string"==typeof a||s(a)&&fg.call(a)==da}function Se(a){return s(a)&&dd(a.length)&&!!Sa[fg.call(a)]}function Te(a){return a===A}function Ue(a,b){return b>a}function Ve(a,b){return b>=a}function We(a){var b=a?Vg(a):0;return dd(b)?b?c.Cc.Bc&&Re(a)?a.split(""):bb(a):[]:gf(a)}function Xe(a){return vb(a,bf(a))}function Ye(a,b,c){var d=Og(a);return c&&ad(a,b,c)&&(b=A),b?tb(d,b):d}function Ze(a){return Jb(a,bf(a))}function $e(a,b,c){var d=null==a?A:Kb(a,nd(b),b+"");return d===A?c:d}function _e(a,b){if(null==a)return!1;var c=dg.call(a,b);if(!c&&!bd(b)){if(b=nd(b),a=1==b.length?a:Kb(a,Yb(b,0,-1)),null==a)return!1;b=Bd(b),c=dg.call(a,b)}return c||dd(a.length)&&_c(b,a.length)&&(Ih(a)||Ae(a)||Re(a))}function af(a,b,c){c&&ad(a,b,c)&&(b=A);for(var d=-1,e=Th(a),f=e.length,g={};++d<f;){var h=e[d],i=a[h];b?dg.call(g,i)?g[i].push(h):g[i]=[h]:g[i]=h}return g}function bf(a){if(null==a)return[];Je(a)||(a=Wf(a));var b=a.length,d=c.Cc;b=b&&dd(b)&&(Ih(a)||Ae(a)||Re(a))&&b||0;for(var e=a.constructor,f=-1,g=Ie(e)&&e.prototype||ag,h=g===a,i=Qf(b),j=b>0,k=d.Jc&&(a===_f||a instanceof Sf),l=d.Kc&&Ie(a);++f<b;)i[f]=f+"";for(var m in a)l&&"prototype"==m||k&&("message"==m||"name"==m)||j&&_c(m,b)||"constructor"==m&&(h||!dg.call(a,m))||i.push(m);if(d.Lc&&a!==ag){var n=a===bg?da:a===_f?Y:fg.call(a),o=Mg[n]||Mg[aa];for(n==aa&&(g=ag),b=Qa.length;b--;){m=Qa[b];var p=o[m];h&&p||(p?!dg.call(a,m):a[m]===g[m])||i.push(m)}}return i}function cf(a){a=md(a);for(var b=-1,c=Th(a),d=c.length,e=Qf(d);++b<d;){var f=c[b];e[b]=[f,a[f]]}return e}function df(a,b,c){var d=null==a?A:md(a)[b];return d===A&&(null==a||bd(b,a)||(b=nd(b),a=1==b.length?a:Kb(a,Yb(b,0,-1)),d=null==a?A:md(a)[Bd(b)]),d=d===A?c:d),Ie(d)?d.call(a):d}function ef(a,b,c){if(null==a)return a;var d=b+"";b=null!=a[d]||bd(b,a)?[d]:nd(b);for(var e=-1,f=b.length,g=f-1,h=a;null!=h&&++e<f;){var i=b[e];Je(h)&&(e==g?h[i]=c:null==h[i]&&(h[i]=_c(b[e+1])?[]:{})),h=h[i]}return a}function ff(a,b,c,d){var e=Ih(a)||Se(a);if(b=Qc(b,d,4),null==c)if(e||Je(a)){var f=a.constructor;c=e?Ih(a)?new f:[]:Og(Ie(f)?f.prototype:A)}else c={};return(e?cb:Hb)(a,function(a,d,e){return b(c,a,d,e)}),c}function gf(a){return cc(a,Th(a))}function hf(a){return cc(a,bf(a))}function jf(a,b,c){return b=+b||0,c===A?(c=b,b=0):c=+c||0,a>=zg(b,c)&&a<yg(b,c)}function kf(a,b,c){c&&ad(a,b,c)&&(b=c=A);var d=null==a,e=null==b;if(null==c&&(e&&"boolean"==typeof a?(c=a,a=1):"boolean"==typeof b&&(c=b,e=!0)),d&&e&&(b=1,e=!1),a=+a||0,e?(b=a,a=0):b=+b||0,c||a%1||b%1){var f=Cg();return zg(a+f*(b-a+kg("1e-"+((f+"").length-1))),b)}return Wb(a,b)}function lf(a){return a=i(a),a&&a.charAt(0).toUpperCase()+a.slice(1)}function mf(a){return a=i(a),a&&a.replace(La,n).replace(Ea,"")}function nf(a,b,c){a=i(a),b+="";var d=a.length;return c=c===A?d:zg(0>c?0:+c||0,d),c-=b.length,c>=0&&a.indexOf(b,c)==c}function of(a){return a=i(a),a&&va.test(a)?a.replace(ta,o):a}function pf(a){return a=i(a),a&&Da.test(a)?a.replace(Ca,p):a||"(?:)"}function qf(a,b,c){a=i(a),b=+b;var d=a.length;if(d>=b||!wg(b))return a;var e=(b-d)/2,f=ug(e),g=sg(e);
return c=Ic("",g,c),c.slice(0,f)+a+c}function rf(a,b,c){return(c?ad(a,b,c):null==b)?b=0:b&&(b=+b),a=vf(a),Bg(a,b||(Ia.test(a)?16:10))}function sf(a,b){var c="";if(a=i(a),b=+b,1>b||!a||!wg(b))return c;do b%2&&(c+=a),b=ug(b/2),a+=a;while(b);return c}function tf(a,b,c){return a=i(a),c=null==c?0:zg(0>c?0:+c||0,a.length),a.lastIndexOf(b,c)==c}function uf(a,b,d){var e=c.Mc;d&&ad(a,b,d)&&(b=d=A),a=i(a),b=sb(tb({},d||b),e,rb);var f,g,h=sb(tb({},b.imports),e.imports,rb),j=Th(h),k=cc(h,j),l=0,m=b.Nc||Ma,n="__p += '",o=Xf((b.escape||Ma).source+"|"+m.source+"|"+(m===ya?Ga:Ma).source+"|"+(b.evaluate||Ma).source+"|$","g"),p="//# sourceURL="+("sourceURL"in b?b.sourceURL:"lodash.templateSources["+ ++Ra+"]")+"\n";a.replace(o,function(b,c,d,e,h,i){return d||(d=e),n+=a.slice(l,i).replace(Na,q),c&&(f=!0,n+="' +\n__e("+c+") +\n'"),h&&(g=!0,n+="';\n"+h+";\n__p += '"),d&&(n+="' +\n((__t = ("+d+")) == null ? '' : __t) +\n'"),l=i+b.length,b}),n+="';\n";var r=b.Oc;r||(n="with (obj) {\n"+n+"\n}\n"),n=(g?n.replace(pa,""):n).replace(qa,"$1").replace(ra,"$1;"),n="function("+(r||"obj")+") {\n"+(r?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(f?", __e = _.escape":"")+(g?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+n+"return __p\n}";var s=ci(function(){return Tf(j,p+"return "+n).apply(A,k)});if(s.source=n,Ge(s))throw s;return s}function vf(a,b,c){var d=a;return(a=i(a))?(c?ad(d,b,c):null==b)?a.slice(w(a),x(a)+1):(b+="",a.slice(j(a,b),k(a,b)+1)):a}function wf(a,b,c){var d=a;return a=i(a),a?(c?ad(d,b,c):null==b)?a.slice(w(a)):a.slice(j(a,b+"")):a}function xf(a,b,c){var d=a;return a=i(a),a?(c?ad(d,b,c):null==b)?a.slice(0,x(a)+1):a.slice(0,k(a,b+"")+1):a}function yf(a,b,c){c&&ad(a,b,c)&&(b=A);var d=L,e=M;if(null!=b)if(Je(b)){var f="separator"in b?b.separator:f;d="length"in b?+b.length||0:d,e="omission"in b?i(b.omission):e}else d=+b||0;if(a=i(a),d>=a.length)return a;var g=d-e.length;if(1>g)return e;var h=a.slice(0,g);if(null==f)return h+e;if(Qe(f)){if(a.slice(g).search(f)){var j,k,l=a.slice(0,g);for(f.global||(f=Xf(f.source,(Ha.exec(f)||"")+"g")),f.lastIndex=0;j=f.exec(l);)k=j.index;h=h.slice(0,null==k?g:k)}}else if(a.indexOf(f,g)!=g){var m=h.lastIndexOf(f);m>-1&&(h=h.slice(0,m))}return h+e}function zf(a){return a=i(a),a&&ua.test(a)?a.replace(sa,y):a}function Af(a,b,c){return c&&ad(a,b,c)&&(b=A),a=i(a),a.match(b||Oa)||[]}function Bf(a,b,c){return c&&ad(a,b,c)&&(b=A),s(a)?Ef(a):wb(a,b)}function Cf(a){return function(){return a}}function Df(a){return a}function Ef(a){return Pb(xb(a,!0))}function Ff(a,b){return Qb(a,xb(b,!0))}function Gf(a,b,c){if(null==c){var d=Je(b),e=d?Th(b):A,f=e&&e.length?Jb(b,e):A;(f?f.length:d)||(f=!1,c=b,b=a,a=this)}f||(f=Jb(b,Th(b)));var g=!0,h=-1,i=Ie(a),j=f.length;c===!1?g=!1:Je(c)&&"chain"in c&&(g=c.chain);for(;++h<j;){var k=f[h],l=b[k];a[k]=l,i&&(a.prototype[k]=function(b){return function(){var c=this.nc;if(g||c){var d=a(this.lc),e=d.mc=bb(this.mc);return e.push({vc:b,xc:arguments,wc:a}),d.nc=c,d}return b.apply(a,lb([this.value()],arguments))}}(l))}return a}function Hf(){return eb.Pc=gg,this}function If(){}function Jf(a){return bd(a)?Tb(a):Ub(a)}function Kf(a){return function(b){return Kb(a,nd(b),b+"")}}function Lf(a,b,c){c&&ad(a,b,c)&&(b=c=A),a=+a||0,c=null==c?1:+c||0,null==b?(b=a,a=0):b=+b||0;for(var d=-1,e=yg(sg((b-a)/(c||1)),0),f=Qf(e);++d<e;)f[d]=a,a+=c;return f}function Mf(a,b,c){if(a=ug(a),1>a||!wg(a))return[];var d=-1,e=Qf(zg(a,Fg));for(b=hc(b,c,1);++d<a;)Fg>d?e[d]=b(d):b(d);return e}function Nf(a){var b=++eg;return i(a)+b}function Of(a,b){return(+a||0)+(+b||0)}function Pf(a,b,c){return c&&ad(a,b,c)&&(b=A),b=Qc(b,c,3),1==b.length?pb(Ih(a)?a:ld(a),b):ac(a,b)}a=a?gb.Qc(eb.Object(),a,gb.Rc(eb,Pa)):eb;var Qf=a.Array,Rf=a.Date,Sf=a.Error,Tf=a.Function,Uf=a.Math,Vf=a.Number,Wf=a.Object,Xf=a.RegExp,Yf=a.String,Zf=a.TypeError,$f=Qf.prototype,_f=Sf.prototype,ag=Wf.prototype,bg=Yf.prototype,cg=Tf.prototype.toString,dg=ag.hasOwnProperty,eg=0,fg=ag.toString,gg=eb.Pc,hg=Xf("^"+cg.call(dg).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ig=a.ArrayBuffer,jg=a.clearTimeout,kg=a.parseFloat,lg=Uf.pow,mg=ag.propertyIsEnumerable,ng=Uc(a,"Set"),og=a.setTimeout,pg=$f.splice,qg=a.Uint8Array,rg=Uc(a,"WeakMap"),sg=Uf.ceil,tg=Uc(Wf,"create"),ug=Uf.floor,vg=Uc(Qf,"isArray"),wg=a.isFinite,xg=Uc(Wf,"keys"),yg=Uf.max,zg=Uf.min,Ag=Uc(Rf,"now"),Bg=a.parseInt,Cg=Uf.random,Dg=Vf.NEGATIVE_INFINITY,Eg=Vf.POSITIVE_INFINITY,Fg=4294967295,Gg=Fg-1,Hg=Fg>>>1,Ig=9007199254740991,Jg=rg&&new rg,Kg={},Lg={};Lg[ga]=a.Float32Array,Lg[ha]=a.Float64Array,Lg[ia]=a.Int8Array,Lg[ja]=a.Int16Array,Lg[ka]=a.Int32Array,Lg[la]=qg,Lg[ma]=a.Uint8ClampedArray,Lg[na]=a.Uint16Array,Lg[oa]=a.Uint32Array;var Mg={};Mg[V]=Mg[X]=Mg[_]={constructor:!0,toLocaleString:!0,toString:!0,valueOf:!0},Mg[W]=Mg[da]={constructor:!0,toString:!0,valueOf:!0},Mg[Y]=Mg[Z]=Mg[ba]={constructor:!0,toString:!0},Mg[aa]={constructor:!0},cb(Qa,function(a){for(var b in Mg)if(dg.call(Mg,b)){var c=Mg[b];c[a]=dg.call(c,a)}});var Ng=c.Cc={};!function(a){var b=function(){this.x=a},c={0:a,length:a},d=[];b.prototype={valueOf:a,y:a};for(var e in new b)d.push(e);Ng.Jc=mg.call(_f,"message")||mg.call(_f,"name"),Ng.Kc=mg.call(b,"prototype"),Ng.Lc=!/valueOf/.test(d),Ng.Ic="x"!=d[0],Ng.Sc=(pg.call(c,0,1),!c[0]),Ng.Bc="x"[0]+Wf("x")[0]!="xx"}(1,0),c.Mc={escape:wa,evaluate:xa,Nc:ya,Oc:"",imports:{Pc:c}};var Og=function(){function a(){}return function(b){if(Je(b)){a.prototype=b;var c=new a;a.prototype=A}return c||{}}}(),Pg=nc(Hb),Qg=nc(Ib,!0),Rg=oc(),Sg=oc(!0),Tg=Jg?function(a,b){return Jg.set(a,b),a}:Df,Ug=Jg?function(a){return Jg.get(a)}:If,Vg=Tb("length"),Wg=function(){var a=0,b=0;return function(c,d){var e=uh(),f=O-(e-b);if(b=e,f>0){if(++a>=N)return c}else a=0;return Tg(c,d)}}(),Xg=se(function(a,b){return s(a)&&$c(a)?zb(a,Fb(b,!1,!0)):[]}),Yg=xc(),Zg=xc(!0),$g=se(function(a){for(var b=a.length,c=b,d=Qf(l),e=Sc(),f=e===g,h=[];c--;){var i=a[c]=$c(i=a[c])?i:[];d[c]=f&&i.length>=120?qc(c&&i):null}var j=a[0],k=-1,l=j?j.length:0,m=d[0];a:for(;++k<l;)if(i=j[k],(m?$a(m,i):e(h,i,0))<0){for(var c=b;--c;){var n=d[c];if((n?$a(n,i):e(a[c],i,0))<0)continue a}m&&m.push(i),h.push(i)}return h}),_g=se(function(a,c){c=Fb(c);var d=ub(a,c);return Vb(a,c.sort(b)),d}),ah=Lc(),bh=Lc(!0),ch=se(function(a){return bc(Fb(a,!1,!0))}),dh=se(function(a,b){return $c(a)?zb(a,b):[]}),eh=se(Md),fh=se(function(a){var b=a.length,c=b>2?a[b-2]:A,d=b>1?a[b-1]:A;return b>2&&"function"==typeof c?b-=2:(c=b>1&&"function"==typeof d?(--b,d):A,d=A),a.length=b,Nd(a,c,d)}),gh=se(function(a){return a=Fb(a),this.yc(function(b){return ab(Ih(b)?b:[md(b)],a)})}),hh=se(function(a,b){return $c(a)&&(a=ld(a)),ub(a,Fb(b))}),ih=lc(function(a,b,c){dg.call(a,c)?++a[c]:a[c]=1}),jh=wc(Pg),kh=wc(Qg,!0),lh=Ac(cb,Pg),mh=Ac(db,Qg),nh=lc(function(a,b,c){dg.call(a,c)?a[c].push(b):a[c]=[b]}),oh=lc(function(a,b,c){a[c]=b}),ph=se(function(a,b,c){var d=-1,e="function"==typeof b,f=bd(b),g=$c(a)?Qf(a.length):[];return Pg(a,function(a){var h=e?b:f&&null!=a?a[b]:A;g[++d]=h?h.apply(a,c):Zc(a,b,c)}),g}),qh=lc(function(a,b,c){a[c?0:1].push(b)},function(){return[[],[]]}),rh=Gc(mb,Pg),sh=Gc(nb,Qg),th=se(function(a,b){if(null==a)return[];var c=b[2];return c&&ad(b[0],b[1],c)&&(b.length=1),_b(a,Fb(b),[])}),uh=Ag||function(){return(new Rf).getTime()},vh=se(function(a,b,c){var d=C;if(c.length){var e=u(c,vh.placeholder);d|=H}return Mc(a,d,b,c,e)}),wh=se(function(a,b){b=b.length?Fb(b):Ze(a);for(var c=-1,d=b.length;++c<d;){var e=b[c];a[e]=Mc(a[e],C,a)}return a}),xh=se(function(a,b,c){var d=C|D;if(c.length){var e=u(c,xh.placeholder);d|=H}return Mc(b,d,a,c,e)}),yh=tc(F),zh=tc(G),Ah=se(function(a,b){return yb(a,1,b)}),Bh=se(function(a,b,c){return yb(a,b,c)}),Ch=zc(),Dh=zc(!0),Eh=se(function(a,b){if(b=Fb(b),"function"!=typeof a||!hb(b,h))throw new Zf(S);var c=b.length;return se(function(d){for(var e=zg(d.length,c);e--;)d[e]=b[e](d[e]);return a.apply(this,d)})}),Fh=Fc(H),Gh=Fc(I),Hh=se(function(a,b){return Mc(a,K,A,A,A,Fb(b))}),Ih=vg||function(a){return s(a)&&dd(a.length)&&fg.call(a)==V},Jh=mc(Rb),Kh=mc(function(a,b,c){return c?sb(a,b,c):tb(a,b)}),Lh=uc(Kh,qb),Mh=uc(Jh,gd),Nh=yc(Hb),Oh=yc(Ib),Ph=Bc(Rg),Qh=Bc(Sg),Rh=Cc(Hb),Sh=Cc(Ib),Th=xg?function(a){var b=null==a?A:a.constructor;return"function"==typeof b&&b.prototype===a||("function"==typeof a?c.Cc.Kc:$c(a))?kd(a):Je(a)?xg(a):[]}:kd,Uh=Dc(!0),Vh=Dc(),Wh=se(function(a,b){if(null==a)return{};if("function"!=typeof b[0]){var b=kb(Fb(b),Yf);return hd(a,zb(bf(a),b))}var c=hc(b[0],b[1],3);return id(a,function(a,b,d){return!c(a,b,d)})}),Xh=se(function(a,b){return null==a?{}:"function"==typeof b[0]?id(a,hc(b[0],b[1],3)):hd(a,Fb(b))}),Yh=rc(function(a,b,c){return b=b.toLowerCase(),a+(c?b.charAt(0).toUpperCase()+b.slice(1):b)}),Zh=rc(function(a,b,c){return a+(c?"-":"")+b.toLowerCase()}),$h=Ec(),_h=Ec(!0),ai=rc(function(a,b,c){return a+(c?"_":"")+b.toLowerCase()}),bi=rc(function(a,b,c){return a+(c?" ":"")+(b.charAt(0).toUpperCase()+b.slice(1))}),ci=se(function(a,b){try{return a.apply(A,b)}catch(a){return Ge(a)?a:new Sf(a)}}),di=se(function(a,b){return function(c){return Zc(c,a,b)}}),ei=se(function(a,b){return function(c){return Zc(a,c,b)}}),fi=Kc("ceil"),gi=Kc("floor"),hi=vc(ye,Dg),ii=vc(Ue,Eg),ji=Kc("round");return c.prototype=d.prototype,e.prototype=Og(d.prototype),e.prototype.constructor=e,t.prototype=Og(d.prototype),t.prototype.constructor=t,Ua.prototype.delete=Va,Ua.prototype.get=Wa,Ua.prototype.has=Xa,Ua.prototype.set=Ya,Za.prototype.push=_a,pe.Hc=Ua,c.Tc=le,c.Uc=me,c.assign=Kh,c.Vc=hh,c.Wc=ne,c.bind=vh,c.Xc=wh,c.Yc=xh,c.Ac=Bf,c.chain=Qd,c.Zc=pd,c.compact=qd,c.$c=Cf,c._c=ih,c.create=Ye,c.ad=yh,c.bd=zh,c.dd=oe,c.Qc=Lh,c.ed=Mh,c.defer=Ah,c.fd=Bh,c.gd=Xg,c.hd=rd,c.jd=sd,c.kd=td,c.ld=ud,c.fill=vd,c.filter=$d,c.md=xd,c.nd=yd,c.od=Ch,c.pd=Dh,c.forEach=lh,c.qd=mh,c.rd=Ph,c.sd=Qh,c.td=Rh,c.ud=Sh,c.vd=Ze,c.wd=nh,c.xd=oh,c.yd=Ad,c.zd=$g,c.Ad=af,c.Bd=ph,c.keys=Th,c.Cd=bf,c.map=be,c.Dd=Uh,c.Ed=Vh,c.matches=Ef,c.Fd=Ff,c.Gd=pe,c.Hd=Jh,c.method=di,c.Id=ei,c.Jd=Gf,c.Kd=Eh,c.Ld=qe,c.Md=Wh,c.ba=re,c.Nd=cf,c.Od=Fh,c.Pd=Gh,c.Qd=qh,c.Rc=Xh,c.Rd=ce,c.Sd=Jf,c.Td=Kf,c.Ud=Dd,c.Vd=_g,c.range=Lf,c.Wd=Hh,c.reject=de,c.remove=Ed,c.Xd=Fd,c.Yd=se,c.set=ef,c.Zd=fe,c.slice=Gd,c.$d=ie,c._d=th,c.ae=je,c.be=te,c.ce=Hd,c.de=Id,c.ee=Jd,c.fe=Kd,c.ge=Rd,c.he=ue,c.yc=Sd,c.ie=Mf,c.toArray=We,c.je=Xe,c.transform=ff,c.ke=ch,c.le=Ld,c.me=Md,c.ne=Nd,c.values=gf,c.oe=hf,c.pe=ke,c.qe=dh,c.wrap=ve,c.re=Od,c.se=eh,c.te=Pd,c.ue=fh,c.ve=Dh,c.collect=be,c.we=Dh,c.xe=lh,c.ye=mh,c.extend=Kh,c.tc=Bf,c.ze=Ze,c.object=Pd,c.select=$d,c.Ae=Fd,c.unique=Ld,Gf(c,c),c.add=Of,c.Be=ci,c.Ce=Yh,c.De=lf,c.ceil=fi,c.clone=we,c.Ee=xe,c.Fe=mf,c.endsWith=nf,c.escape=of,c.Ge=pf,c.every=Zd,c.find=jh,c.findIndex=Yg,c.He=Nh,c.Ie=kh,c.Je=Zg,c.Ke=Oh,c.Le=_d,c.Me=wd,c.floor=gi,c.get=$e,c.Ne=ye,c.Oe=ze,c.has=_e,c.identity=Df,c.includes=ae,c.indexOf=zd,c.inRange=jf,c.Pe=Ae,c.isArray=Ih,c.pa=Be,c.D=Ce,c.Qe=De,c.Re=Ee,c.isEqual=Fe,c.kb=Ge,c.isFinite=He,c.s=Ie,c.Se=Ke,c.isNaN=Le,c.Te=Me,c.qa=Ne,c.q=Oe,c.F=Je,c.Ue=Pe,c.t=Qe,c.u=Re,c.Ve=Se,c.p=Te,c.We=Zh,c.Xe=Bd,c.lastIndexOf=Cd,c.Ye=Ue,c.Ze=Ve,c.max=hi,c.min=ii,c.$e=Hf,c._e=If,c.now=uh,c.pad=qf,c.af=$h,c.bf=_h,c.parseInt=rf,c.random=kf,c.reduce=rh,c.reduceRight=sh,c.repeat=sf,c.result=df,c.round=ji,c.cf=z,c.size=ge,c.df=ai,c.some=he,c.ef=ah,c.ff=bh,c.gf=bi,c.startsWith=tf,c.hf=Pf,c.if=uf,c.trim=vf,c.trimLeft=wf,c.trimRight=xf,c.trunc=yf,c.unescape=zf,c.jf=Nf,c.kf=Af,c.all=Zd,c.lf=he,c.contains=ae,c.mf=Fe,c.nf=jh,c.pf=rh,c.qf=sh,c.head=wd,c.rf=ae,c.sf=rh,Gf(c,function(){var a={};return Hb(c,function(b,d){c.prototype[d]||(a[d]=b)}),a}(),!1),c.tf=ee,c.prototype.tf=function(a){return this.nc||null!=a?this.yc(function(b){return ee(b,a)}):ee(this.value())},c.VERSION=B,cb(["bind","bindKey","curry","curryRight","partial","partialRight"],function(a){c[a].placeholder=c}),cb(["drop","take"],function(a,b){t.prototype[a]=function(c){var d=this.pc;if(d&&!b)return new t(this);c=null==c?1:yg(ug(c)||0,0);var e=this.clone();return d?e.rc=zg(e.rc,c):e.sc.push({size:c,type:a+(e.oc<0?"Right":"")}),e},t.prototype[a+"Right"]=function(b){return this.reverse()[a](b).reverse()}}),cb(["filter","map","takeWhile"],function(a,b){var c=b+1,d=c!=R;t.prototype[a]=function(a,b){var e=this.clone();return e.qc.push({tc:Qc(a,b,1),type:c}),e.pc=e.pc||d,e}}),cb(["first","last"],function(a,b){var c="take"+(b?"Right":"");t.prototype[a]=function(){return this[c](1).value()[0]}}),cb(["initial","rest"],function(a,b){var c="drop"+(b?"":"Right");t.prototype[a]=function(){return this.pc?new t(this):this[c](1)}}),cb(["pluck","where"],function(a,b){var c=b?"filter":"map",d=b?Pb:Jf;t.prototype[a]=function(a){return this[c](d(a))}}),t.prototype.compact=function(){return this.filter(Df)},t.prototype.reject=function(a,b){return a=Qc(a,b,1),this.filter(function(b){return!a(b)})},t.prototype.slice=function(a,b){a=null==a?0:+a||0;var c=this;return c.pc&&(a>0||0>b)?new t(c):(0>a?c=c.de(-a):a&&(c=c.hd(a)),b!==A&&(b=+b||0,c=0>b?c.jd(-b):c.ce(b-a)),c)},t.prototype.ee=function(a,b){return this.reverse().fe(a,b).reverse()},t.prototype.toArray=function(){return this.ce(Eg)},Hb(t.prototype,function(a,b){var d=/^(?:filter|map|reject)|While$/.test(b),f=/^(?:first|last)$/.test(b),g=c[f?"take"+("last"==b?"Right":""):b];g&&(c.prototype[b]=function(){var b=f?[1]:arguments,c=this.nc,h=this.lc,i=!!this.mc.length,j=h instanceof t,k=b[0],l=j||Ih(h);l&&d&&"function"==typeof k&&1!=k.length&&(j=l=!1);var m=function(a){return f&&c?g(a,1)[0]:g.apply(A,lb([a],b))},n={vc:Sd,xc:[m],wc:A},o=j&&!i;if(f&&!c)return o?(h=h.clone(),h.mc.push(n),a.call(h)):g.call(A,this.value())[0];if(!f&&l){h=o?h:new t(this);var p=a.apply(h,b);return p.mc.push(n),new e(p,c)}return this.yc(m)})}),cb(["join","pop","push","replace","shift","sort","splice","split","unshift"],function(a){var b=(/^(?:replace|split)$/.test(a)?bg:$f)[a],d=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",e=!Ng.Sc&&/^(?:pop|shift|splice)$/.test(a),f=/^(?:join|pop|replace|shift)$/.test(a),g=e?function(){var a=b.apply(this,arguments);return 0===this.length&&delete this[0],a}:b;c.prototype[a]=function(){var a=arguments;return f&&!this.nc?g.apply(this.value(),a):this[d](function(b){return g.apply(b,a)})}}),Hb(t.prototype,function(a,b){var d=c[b];if(d){var e=d.name+"",f=Kg[e]||(Kg[e]=[]);f.push({name:b,vc:d})}}),Kg[Hc(A,D).name]=[{name:"wrapper",vc:A}],t.prototype.clone=$,t.prototype.reverse=ca,t.prototype.value=ea,c.prototype.chain=Td,c.prototype.uf=Ud,c.prototype.concat=gh,c.prototype.zc=Vd,c.prototype.reverse=Wd,c.prototype.toString=Xd,c.prototype.vf=c.prototype.toJSON=c.prototype.valueOf=c.prototype.value=Yd,c.prototype.collect=c.prototype.map,c.prototype.head=c.prototype.Me,c.prototype.select=c.prototype.filter,c.prototype.Ae=c.prototype.Xd,c}var A,B="3.10.2",C=1,D=2,E=4,F=8,G=16,H=32,I=64,J=128,K=256,L=30,M="...",N=150,O=16,P=200,Q=1,R=2,S="Expected a function",T="__lodash_placeholder__",U="[object Arguments]",V="[object Array]",W="[object Boolean]",X="[object Date]",Y="[object Error]",Z="[object Function]",$="[object Map]",_="[object Number]",aa="[object Object]",ba="[object RegExp]",ca="[object Set]",da="[object String]",ea="[object WeakMap]",fa="[object ArrayBuffer]",ga="[object Float32Array]",ha="[object Float64Array]",ia="[object Int8Array]",ja="[object Int16Array]",ka="[object Int32Array]",la="[object Uint8Array]",ma="[object Uint8ClampedArray]",na="[object Uint16Array]",oa="[object Uint32Array]",pa=/\b__p \+= '';/g,qa=/\b(__p \+=) '' \+/g,ra=/(__e\(.*?\)|\b__t\)) \+\n'';/g,sa=/&(?:amp|lt|gt|quot|#39|#96);/g,ta=/[&<>"'`]/g,ua=RegExp(sa.source),va=RegExp(ta.source),wa=/<%-([\s\S]+?)%>/g,xa=/<%([\s\S]+?)%>/g,ya=/<%=([\s\S]+?)%>/g,za=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,Aa=/^\w*$/,Ba=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g,Ca=/^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,Da=RegExp(Ca.source),Ea=/[\u0300-\u036f\ufe20-\ufe23]/g,Fa=/\\(\\)?/g,Ga=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ha=/\w*$/,Ia=/^0[xX]/,Ja=/^\[object .+?Constructor\]$/,Ka=/^\d+$/,La=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g,Ma=/($^)/,Na=/['\n\r\u2028\u2029\\]/g,Oa=function(){var a="[A-Z\\xc0-\\xd6\\xd8-\\xde]",b="[a-z\\xdf-\\xf6\\xf8-\\xff]+";return RegExp(a+"+(?="+a+b+")|"+a+"?"+b+"|"+a+"+|[0-9]+","g")}(),Pa=["Array","ArrayBuffer","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Math","Number","Object","RegExp","Set","String","_","clearTimeout","isFinite","parseFloat","parseInt","setTimeout","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap"],Qa=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ra=-1,Sa={};Sa[ga]=Sa[ha]=Sa[ia]=Sa[ja]=Sa[ka]=Sa[la]=Sa[ma]=Sa[na]=Sa[oa]=!0,Sa[U]=Sa[V]=Sa[fa]=Sa[W]=Sa[X]=Sa[Y]=Sa[Z]=Sa[$]=Sa[_]=Sa[aa]=Sa[ba]=Sa[ca]=Sa[da]=Sa[ea]=!1;var Ta={};Ta[U]=Ta[V]=Ta[fa]=Ta[W]=Ta[X]=Ta[ga]=Ta[ha]=Ta[ia]=Ta[ja]=Ta[ka]=Ta[_]=Ta[aa]=Ta[ba]=Ta[da]=Ta[la]=Ta[ma]=Ta[na]=Ta[oa]=!0,Ta[Y]=Ta[Z]=Ta[$]=Ta[ca]=Ta[ea]=!1;var Ua={wf:"A",xf:"A",yf:"A",zf:"A",Af:"A",Bf:"A",Cf:"a",Df:"a",Ef:"a",Ff:"a",Gf:"a",Hf:"a",If:"C",Jf:"c",Kf:"D",Lf:"d",Mf:"E",Nf:"E",Of:"E",Pf:"E",Qf:"e",Rf:"e",Sf:"e",Tf:"e",Uf:"I",Vf:"I",Wf:"I",Xf:"I",Yf:"i",Zf:"i",$f:"i",_f:"i",ag:"N",bg:"n",cg:"O",dg:"O",eg:"O",fg:"O",gg:"O",hg:"O",ig:"o",jg:"o",kg:"o",lg:"o",mg:"o",ng:"o",og:"U",pg:"U",qg:"U",rg:"U",sg:"u",tg:"u",ug:"u",vg:"u",wg:"Y",xg:"y",yg:"y",zg:"Ae",Ag:"ae",Bg:"Th",Cg:"th",Dg:"ss"},Va={Eg:"&",Fg:"<",Gg:">",Hg:""",Ig:"'",Jg:"`"},Wa={Kg:"&",Lg:"<",Mg:">",Ng:'"',Og:"'",Pg:"`"},Xa={Qg:!0,object:!0},Ya={0:"x30",1:"x31",2:"x32",3:"x33",4:"x34",5:"x35",6:"x36",7:"x37",8:"x38",9:"x39",Rg:"x41",Sg:"x42",Tg:"x43",Ug:"x44",E:"x45",Vg:"x46",a:"x61",b:"x62",c:"x63",d:"x64",e:"x65",f:"x66",n:"x6e",r:"x72",Wg:"x74",Xg:"x75",Yg:"x76",x:"x78"},Za={Zg:"\\",Ig:"'",$g:"n",_g:"r",ah:"u2028",bh:"u2029"},$a=Xa[typeof d]&&d&&!d.nodeType&&d,_a=Xa[typeof c]&&c&&!c.nodeType&&c,ab=$a&&_a&&"object"==typeof e&&e&&e.Object&&e,bb=Xa[typeof self]&&self&&self.Object&&self,cb=Xa[typeof window]&&window&&window.Object&&window,db=_a&&_a.g===$a&&$a,eb=ab||cb!==(this&&this.window)&&cb||bb||this,fb=function(){try{Object({toString:0}+"")}catch(a){return function(){return!1}}return function(a){return"function"!=typeof a.toString&&"string"==typeof(a+"")}}(),gb=z();"function"==typeof a&&"object"==typeof a.amd&&a.amd?(eb.Pc=gb,a(function(){return gb})):$a&&_a?db?(_a.g=gb).Pc=gb:$a.Pc=gb:eb.Pc=gb}).call(this)},{}],16:[function(a,b){var c=b.g={};c.i=function(){var a="undefined"!=typeof window&&window.setImmediate,b="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(a)return function(a){return window.setImmediate(a)};if(b){var c=[];return window.addEventListener("message",function(a){var b=a.source;if((b===window||null===b)&&"process-tick"===a.data&&(a.stopPropagation(),c.length>0)){var d=c.shift();d()}},!0),function(a){c.push(a),window.postMessage("process-tick","*")}}return function(a){setTimeout(a,0)}}(),c.title="browser",c.dh=!0,c.eh={},c.fh=[],c.gh=function(){throw Error("process.binding is not supported")},c.fa=function(){return"/"},c.hh=function(){throw Error("process.chdir is not supported")}},{}],17:[function(a,b){"use strict";function c(){}function d(a){try{return a.then}catch(a){return q=a,r}}function e(a,b){try{return a(b)}catch(a){return q=a,r}}function f(a,b,c){try{a(b,c)}catch(a){return q=a,r}}function g(a){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");this.ih=0,this.jh=0,this.kh=null,this.lh=null,a!==c&&o(a,this)}function h(a,b,d){return new a.constructor(function(e,f){var h=new g(c);h.then(e,f),i(a,new n(b,d,h))})}function i(a,b){for(;3===a.jh;)a=a.kh;return g.mh&&g.mh(a),0===a.jh?0===a.ih?(a.ih=1,void(a.lh=b)):1===a.ih?(a.ih=2,void(a.lh=[a.lh,b])):void a.lh.push(b):void j(a,b)}function j(a,b){p(function(){var c=1===a.jh?b.nh:b.oh;if(null===c)return void(1===a.jh?k(b.ph,a.kh):l(b.ph,a.kh));var d=e(c,a.kh);d===r?l(b.ph,q):k(b.ph,d)})}function k(a,b){if(b===a)return l(a,new TypeError("A promise cannot be resolved with itself."));if(b&&("object"==typeof b||"function"==typeof b)){var c=d(b);if(c===r)return l(a,q);if(c===a.then&&b instanceof g)return a.jh=3,a.kh=b,void m(a);if("function"==typeof c)return void o(c.bind(b),a)}a.jh=1,a.kh=b,m(a)}function l(a,b){a.jh=2,a.kh=b,g.qh&&g.qh(a,b),m(a)}function m(a){if(1===a.ih&&(i(a,a.lh),a.lh=null),2===a.ih){for(var b=0;b<a.lh.length;b++)i(a,a.lh[b]);a.lh=null}}function n(a,b,c){this.nh="function"==typeof a?a:null,this.oh="function"==typeof b?b:null,this.ph=c}function o(a,b){var c=!1,d=f(a,function(a){c||(c=!0,k(b,a))},function(a){c||(c=!0,l(b,a))});c||d!==r||(c=!0,l(b,q))}var p=a("asap/raw"),q=null,r={};b.g=g,g.mh=null,g.qh=null,g.rh=c,g.prototype.then=function(a,b){if(this.constructor!==g)return h(this,a,b);var d=new g(c);return i(this,new n(a,b,d)),d}},{sh:1}],18:[function(a,b){"use strict";function c(a){var b=new d(d.rh);return b.jh=1,b.kh=a,b}var d=a("./core.js");b.g=d;var e=c(!0),f=c(!1),g=c(null),h=c(void 0),i=c(0),j=c("");d.resolve=function(a){if(a instanceof d)return a;if(null===a)return g;if(void 0===a)return h;if(a===!0)return e;if(a===!1)return f;if(0===a)return i;if(""===a)return j;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new d(b.bind(a))}catch(a){return new d(function(b,c){c(a)})}return c(a)},d.all=function(a){var b=Array.prototype.slice.call(a);return new d(function(a,c){function e(g,h){if(h&&("object"==typeof h||"function"==typeof h)){if(h instanceof d&&h.then===d.prototype.then){for(;3===h.jh;)h=h.kh;return 1===h.jh?e(g,h.kh):(2===h.jh&&c(h.kh),void h.then(function(a){e(g,a)},c))}var i=h.then;if("function"==typeof i){var j=new d(i.bind(h));return void j.then(function(a){e(g,a)},c)}}b[g]=h,0===--f&&a(b)}if(0===b.length)return a([]);for(var f=b.length,g=0;g<b.length;g++)e(g,b[g])})},d.reject=function(a){return new d(function(b,c){c(a)})},d.race=function(a){return new d(function(b,c){a.forEach(function(a){d.resolve(a).then(b,c)})})},d.prototype.catch=function(a){return this.then(null,a)}},{th:17}],19:[function(a,b){function c(){throw Error('Looks like you are expecting the previous "elasticsearch" module. It is now the "es" module. To create a client with this module use `new es.Client(params)`.')}c.uh=a("./lib/client"),c.vh=a("./lib/connection_pool"),c.wh=a("./lib/transport"),c.xh=a("./lib/errors"),b.g=c},{yh:28,zh:31,Ah:34,Bh:47}],20:[function(a,b){var c=a("../client_action").Ch(function(b){return a("../utils").Hd(b,{Dh:{Eh:{type:"list",name:"filter_path"}}})}),d=a("../client_action").Fh,e=b.g={};e.Gh=["cat","cluster","indices","nodes","snapshot"],e.Hh=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},refresh:{type:"boolean"},Jh:{type:"enum",default:"sync",options:["sync","async"]},Kh:{type:"string"},timeout:{type:"time"},type:{type:"string"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_bulk",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_bulk",Nh:{index:{type:"string"}}},{Mh:"/_bulk"}],Oh:!0,Ph:!0,method:"POST"}),e.Qh=d(),e.Qh.prototype.Rh=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_cat/aliases"}]}),e.Qh.prototype.Wh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/allocation/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cat/allocation"}]}),e.Qh.prototype.count=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/count/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/count"}]}),e.Qh.prototype.Zh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},$h:{type:"list"}},Lh:[{Mh:"/_cat/fielddata/<%=fields%>",Nh:{$h:{type:"list"}}},{Mh:"/_cat/fielddata"}]}),e.Qh.prototype._h=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ai:{type:"boolean",default:!0},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/health"}}),e.Qh.prototype.Vh=c({Dh:{Vh:{type:"boolean",default:!1}},url:{Mh:"/_cat"}}),e.Qh.prototype.bi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ci:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/indices/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/indices"}]}),e.Qh.prototype.di=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/master"}}),e.Qh.prototype.ei=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodes"}}),e.Qh.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/pending_tasks"}}),e.Qh.prototype.plugins=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/plugins"}}),e.Qh.prototype.gi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/recovery/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/recovery"}]}),e.Qh.prototype.hi=c({Dh:{Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!0}},Lh:[{Mh:"/_cat/segments/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/segments"}]}),e.Qh.prototype.ii=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/shards/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/shards"}]}),e.Qh.prototype.ji=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},ki:{type:"boolean",default:!1,name:"full_id"}},url:{Mh:"/_cat/thread_pool"}}),e.li=c({Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"list"}}},{Mh:"/_search/scroll"}],method:"DELETE"}),e.ni=d(),e.ni.prototype.oi=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"}}),e.ni.prototype._h=c({Dh:{level:{type:"enum",default:"cluster",options:["cluster","indices","shards"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},qi:{type:"number",name:"wait_for_active_shards"},ri:{type:"string",name:"wait_for_nodes"},si:{type:"number",name:"wait_for_relocating_shards"},ti:{type:"enum",default:null,options:["green","yellow","red"],name:"wait_for_status"}},Lh:[{Mh:"/_cluster/health/<%=index%>",Nh:{index:{type:"string"}}},{Mh:"/_cluster/health"}]}),e.ni.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_cluster/pending_tasks"}}),e.ni.prototype.ui=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"},method:"PUT"}),e.ni.prototype.vi=c({Dh:{wi:{type:"boolean",name:"dry_run"},xi:{type:"boolean"},yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","master_node","version"]},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/reroute"},method:"POST"}),e.ni.prototype.state=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/_cluster/state/<%=metric%>/<%=index%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]},index:{type:"list"}}},{Mh:"/_cluster/state/<%=metric%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]}}},{Mh:"/_cluster/state"}]}),e.ni.prototype.Ci=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_cluster/stats/nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cluster/stats"}]}),e.count=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_count",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_count",Nh:{index:{type:"list"}}},{Mh:"/_count"}],method:"POST"}),e.Ni=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.delete=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},parent:{type:"string"},refresh:{type:"boolean"},Jh:{type:"enum",default:"sync",options:["sync","async"]},Kh:{type:"string"},timeout:{type:"time"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Ri=c({Dh:{Hi:{type:"string"},Ih:{type:"enum",options:["one","quorum","all"]},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jh:{type:"enum",default:"sync",options:["sync","async"]},Gi:{type:"string"},Kh:{type:"string"},timeout:{type:"time"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_query",Nh:{index:{type:"list"}}}],method:"DELETE"}),e.Si=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Ti=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},method:"DELETE"}),e.Ui=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"HEAD"
}),e.xi=c({Dh:{Ii:{type:"boolean",name:"analyze_wildcard"},Hi:{type:"string"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},$h:{type:"list"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},parent:{type:"string"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_explain",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Zi=c({Dh:{$h:{type:"list"},level:{type:"enum",default:"cluster",options:["indices","cluster"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_field_stats",Nh:{index:{type:"list"}}},{Mh:"/_field_stats"}],method:"POST"}),e.get=c({Dh:{$h:{type:"list"},parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.$i=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}}}),e._i=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_source",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.aj=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}}}),e.index=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},parent:{type:"string"},refresh:{type:"boolean"},Jh:{type:"enum",default:"sync",options:["sync","async"]},Kh:{type:"string"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"string"},type:{type:"string"}}}],Oh:!0,method:"POST"}),e.bi=d(),e.bi.prototype.dj=c({Dh:{Hi:{type:"string"},ej:{type:"list",name:"char_filters"},fj:{type:"string"},filters:{type:"list"},index:{type:"string"},gj:{type:"boolean",name:"prefer_local"},text:{type:"string"},hj:{type:"string"},format:{type:"enum",default:"detailed",options:["detailed","text"]}},Lh:[{Mh:"/<%=index%>/_analyze",Nh:{index:{type:"string"}}},{Mh:"/_analyze"}],method:"POST"}),e.bi.prototype.ij=c({Dh:{jj:{type:"boolean",name:"field_data"},Zh:{type:"boolean"},$h:{type:"list"},filter:{type:"boolean"},kj:{type:"boolean",name:"filter_cache"},lj:{type:"boolean",name:"filter_keys"},id:{type:"boolean"},mj:{type:"boolean",name:"id_cache"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},index:{type:"list"},nj:{type:"boolean"},oj:{type:"boolean",name:"query_cache"}},Lh:[{Mh:"/<%=index%>/_cache/clear",Nh:{index:{type:"list"}}},{Mh:"/_cache/clear"}],method:"POST"}),e.bi.prototype.close=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_close",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.create=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.delete=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"DELETE"}),e.bi.prototype.pj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.qj=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/<%=type%>/_mapping",Nh:{index:{type:"list"},type:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ti=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"DELETE"}),e.bi.prototype.rj=c({Dh:{Th:{type:"time",name:"master_timeout"},name:{type:"list"}},url:{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ui=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"HEAD"}),e.bi.prototype.sj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}}],method:"HEAD"}),e.bi.prototype.tj=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"HEAD"}),e.bi.prototype.uj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},method:"HEAD"}),e.bi.prototype.flush=c({Dh:{vj:{type:"boolean"},wj:{type:"boolean",name:"wait_if_ongoing"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush",Nh:{index:{type:"list"}}},{Mh:"/_flush"}],method:"POST"}),e.bi.prototype.xj=c({Lh:[{Mh:"/<%=index%>/_flush/synced",Nh:{index:{type:"list"}}},{Mh:"/_flush/synced"}],method:"POST"}),e.bi.prototype.get=c({Dh:{Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=feature%>",Nh:{index:{type:"list"},yj:{type:"list"}}},{Mh:"/<%=index%>",Nh:{index:{type:"list"}}}]}),e.bi.prototype.zj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}},{Mh:"/_alias"}]}),e.bi.prototype.Aj=c({Dh:{timeout:{type:"time"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_aliases/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_aliases",Nh:{index:{type:"list"}}},{Mh:"/_aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_aliases"}]}),e.bi.prototype.Bj=c({Dh:{Cj:{type:"boolean",name:"include_defaults"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>/field/<%=field%>",Nh:{index:{type:"list"},type:{type:"list"},fj:{type:"list"}}},{Mh:"/<%=index%>/_mapping/field/<%=field%>",Nh:{index:{type:"list"},fj:{type:"list"}}},{Mh:"/_mapping/<%=type%>/field/<%=field%>",Nh:{type:{type:"list"},fj:{type:"list"}}},{Mh:"/_mapping/field/<%=field%>",Nh:{fj:{type:"list"}}}]}),e.bi.prototype.Dj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_mapping",Nh:{index:{type:"list"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"list"}}},{Mh:"/_mapping"}]}),e.bi.prototype.oi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_settings/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_settings"}]}),e.bi.prototype.aj=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},{Mh:"/_template"}]}),e.bi.prototype.Ej=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}]}),e.bi.prototype.Fj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer",Nh:{index:{type:"list"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_warmer"}]}),e.bi.prototype.open=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"closed",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_open",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.Gj=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"},vj:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_optimize",Nh:{index:{type:"list"}}},{Mh:"/_optimize"}],method:"POST"}),e.bi.prototype.Lj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},method:"PUT"}),e.bi.prototype.Mj=c({Dh:{Nj:{type:"boolean",name:"ignore_conflicts"},timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"string"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.ui=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"}},Lh:[{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings"}],Oh:!0,method:"PUT"}),e.bi.prototype.Oj=c({Dh:{order:{type:"number"},create:{type:"boolean",default:!1},timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},Oh:!0,method:"PUT"}),e.bi.prototype.Pj=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"string"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.gi=c({Dh:{Qj:{type:"boolean",default:!1},Rj:{type:"boolean",default:!1,name:"active_only"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_recovery",Nh:{index:{type:"list"}}},{Mh:"/_recovery"}]}),e.bi.prototype.refresh=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},vj:{type:"boolean",default:!1},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_refresh",Nh:{index:{type:"list"}}},{Mh:"/_refresh"}],method:"POST"}),e.bi.prototype.hi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_segments",Nh:{index:{type:"list"}}},{Mh:"/_segments"}]}),e.bi.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"list"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"indices",options:["cluster","indices","shards"]},types:{type:"list"}},Lh:[{Mh:"/<%=index%>/_stats/<%=metric%>",Nh:{index:{type:"list"},yi:{type:"list",options:["_all","completion","docs","fielddata","filter_cache","flush","get","id_cache","indexing","merge","percolate","query_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","completion","docs","fielddata","filter_cache","flush","get","id_cache","indexing","merge","percolate","query_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/<%=index%>/_stats",Nh:{index:{type:"list"}}},{Mh:"/_stats"}]}),e.bi.prototype.status=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1},Jj:{name:"operation_threading"},gi:{type:"boolean"},Vj:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_status",Nh:{index:{type:"list"}}},{Mh:"/_status"}]}),e.bi.prototype.Wj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_aliases"},Oh:!0,method:"POST"}),e.bi.prototype.Xj=c({Dh:{Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},zi:{type:"boolean",name:"ignore_unavailable"},Yj:{type:"boolean",name:"wait_for_completion"},Zj:{type:"boolean",name:"only_ancient_segments"}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}],method:"POST"}),e.bi.prototype.$j=c({Dh:{xi:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},_j:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_validate/query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_validate/query",Nh:{index:{type:"list"}}},{Mh:"/_validate/query"}],method:"POST"}),e.info=c({url:{Mh:"/"}}),e.ak=c({Dh:{$h:{type:"list"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mget",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mget",Nh:{index:{type:"string"}}},{Mh:"/_mget"}],Oh:!0,method:"POST"}),e.bk=c({Dh:{ck:{type:"number",name:"boost_terms"},dk:{type:"number",name:"max_doc_freq"},ek:{type:"number",name:"max_query_terms"},fk:{type:"number",name:"max_word_length"},gk:{type:"number",name:"min_doc_freq"},hk:{type:"number",name:"min_term_freq"},ik:{type:"number",name:"min_word_length"},jk:{type:"list",name:"mlt_fields"},kk:{type:"number",name:"percent_terms_to_match"},Kh:{type:"string"},lk:{type:"number",name:"search_from"},mk:{type:"list",name:"search_indices"},nk:{type:"string",name:"search_scroll"},pk:{type:"number",name:"search_size"},qk:{type:"string",name:"search_source"},rk:{type:"string",name:"search_type"},sk:{type:"list",name:"search_types"},tk:{type:"list",name:"stop_words"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_mlt",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.uk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mpercolate",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mpercolate",Nh:{index:{type:"string"}}},{Mh:"/_mpercolate"}],Oh:!0,Ph:!0,method:"POST"}),e.vk=c({Dh:{rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_msearch",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_msearch",Nh:{index:{type:"list"}}},{Mh:"/_msearch"}],Oh:!0,Ph:!0,method:"POST"}),e.wk=c({Dh:{xk:{type:"list",required:!1},yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mtermvectors",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mtermvectors",Nh:{index:{type:"string"}}},{Mh:"/_mtermvectors"}],method:"POST"}),e.ei=d(),e.ei.prototype.Dk=c({Dh:{interval:{type:"time"},Ek:{type:"number"},Fk:{type:"number"},Gk:{type:"boolean",name:"ignore_idle_threads"},type:{type:"enum",options:["cpu","wait","block"]},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/hotthreads",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/hotthreads"}]}),e.ei.prototype.info=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["settings","os","process","jvm","thread_pool","network","transport","http","plugins"]}}},{Mh:"/_nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/<%=metric%>",Nh:{yi:{type:"list",options:["settings","os","process","jvm","thread_pool","network","transport","http","plugins"]}}},{Mh:"/_nodes"}]}),e.ei.prototype.Hk=c({Dh:{fd:{type:"time"},Ik:{type:"boolean"}},Lh:[{Mh:"/_cluster/nodes/<%=nodeId%>/_shutdown",Nh:{Yh:{type:"list"}}},{Mh:"/_shutdown"}],method:"POST"}),e.ei.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"boolean"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"node",options:["node","indices","shards"]},types:{type:"list"},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","network","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","filter_cache","flush","get","id_cache","indexing","merge","percolate","query_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","network","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats/<%=metric%>/<%=indexMetric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","network","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","filter_cache","flush","get","id_cache","indexing","merge","percolate","query_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","network","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats"}]}),e.Kk=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Lk:{type:"enum",options:["ids"],name:"percolate_format"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},Mk:{type:"string",name:"percolate_routing"},Nk:{type:"string",name:"percolate_preference"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.ping=c({url:{Mh:"/"},Ok:3e3,method:"HEAD"}),e.Pk=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},Oh:!0,method:"PUT"}),e.Oj=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},Oh:!0,method:"PUT"}),e.scroll=c({Dh:{scroll:{type:"duration"},mi:{type:"string",name:"scroll_id"}},Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"string"}}},{Mh:"/_search/scroll"}],Qk:"scrollId",method:"POST"}),e.search=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},oj:{type:"boolean",name:"query_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search",Nh:{index:{type:"list"}}},{Mh:"/_search"}],method:"POST"}),e.Wk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/exists",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/exists",Nh:{index:{type:"list"}}},{Mh:"/_search/exists"}],method:"POST"}),e.Xk=c({Dh:{Fi:{type:"string"},Kh:{type:"string"},Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search_shards",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_search_shards",Nh:{index:{type:"string"}}},{Mh:"/_search_shards"}],method:"POST"}),e.Yk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/template",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/template",Nh:{index:{type:"list"}}},{Mh:"/_search/template"}],method:"POST"}),e.Vj=d(),e.Vj.prototype.create=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.$k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},verify:{type:"boolean"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"string"}}},Oh:!0,method:"POST"}),e.Vj.prototype.delete=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"DELETE"}),e.Vj.prototype._k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},method:"DELETE"}),e.Vj.prototype.get=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"list"}}}}),e.Vj.prototype.al=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},{Mh:"/_snapshot"}]}),e.Vj.prototype.restore=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_restore",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.status=c({Dh:{Th:{type:"time",name:"master_timeout"}},Lh:[{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_status",Nh:{Zk:{type:"string"},Vj:{type:"list"}}},{Mh:"/_snapshot/<%=repository%>/_status",Nh:{Zk:{type:"string"}}},{Mh:"/_snapshot/_status"}]}),e.Vj.prototype.bl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>/_verify",Nh:{Zk:{type:"string"}}},method:"POST"}),e.cl=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"string"}},Lh:[{Mh:"/<%=index%>/_suggest",Nh:{index:{type:"list"}}},{Mh:"/_suggest"}],Oh:!0,method:"POST"}),e.dl=c({Dh:{yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_termvector",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_termvector",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.update=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},$h:{type:"list"},lang:{type:"string"},parent:{type:"string"},refresh:{type:"boolean"},Jh:{type:"enum",default:"sync",options:["sync","async"]},el:{type:"number",name:"retry_on_conflict"},Kh:{type:"string"},fl:{},gl:{name:"script_id"},hl:{type:"boolean",name:"scripted_upsert"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_update",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.create=c.il(e.index,{transform:function(a){a.jl="create"}})},{kl:29,ll:50}],21:[function(a,b){var c=a("../client_action").Ch(function(b){return a("../utils").Hd(b,{Dh:{Eh:{type:"list",name:"filter_path"}}})}),d=a("../client_action").Fh,e=b.g={};e.Gh=["cat","cluster","indices","nodes","snapshot"],e.Hh=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},type:{type:"string"},$h:{type:"list"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_bulk",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_bulk",Nh:{index:{type:"string"}}},{Mh:"/_bulk"}],Oh:!0,Ph:!0,method:"POST"}),e.Qh=d(),e.Qh.prototype.Rh=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_cat/aliases"}]}),e.Qh.prototype.Wh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/allocation/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cat/allocation"}]}),e.Qh.prototype.count=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/count/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/count"}]}),e.Qh.prototype.Zh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},$h:{type:"list"}},Lh:[{Mh:"/_cat/fielddata/<%=fields%>",Nh:{$h:{type:"list"}}},{Mh:"/_cat/fielddata"}]}),e.Qh.prototype._h=c({
Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ai:{type:"boolean",default:!0},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/health"}}),e.Qh.prototype.Vh=c({Dh:{Vh:{type:"boolean",default:!1}},url:{Mh:"/_cat"}}),e.Qh.prototype.bi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ci:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/indices/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/indices"}]}),e.Qh.prototype.di=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/master"}}),e.Qh.prototype.ml=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodeattrs"}}),e.Qh.prototype.ei=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodes"}}),e.Qh.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/pending_tasks"}}),e.Qh.prototype.plugins=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/plugins"}}),e.Qh.prototype.gi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/recovery/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/recovery"}]}),e.Qh.prototype.hi=c({Dh:{Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/segments/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/segments"}]}),e.Qh.prototype.ii=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/shards/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/shards"}]}),e.Qh.prototype.ji=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},ki:{type:"boolean",default:!1,name:"full_id"}},url:{Mh:"/_cat/thread_pool"}}),e.li=c({Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"list"}}},{Mh:"/_search/scroll"}],method:"DELETE"}),e.ni=d(),e.ni.prototype.oi=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"}}),e.ni.prototype._h=c({Dh:{level:{type:"enum",default:"cluster",options:["cluster","indices","shards"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},qi:{type:"number",name:"wait_for_active_shards"},ri:{type:"string",name:"wait_for_nodes"},si:{type:"number",name:"wait_for_relocating_shards"},ti:{type:"enum",default:null,options:["green","yellow","red"],name:"wait_for_status"}},Lh:[{Mh:"/_cluster/health/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cluster/health"}]}),e.ni.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_cluster/pending_tasks"}}),e.ni.prototype.ui=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"},method:"PUT"}),e.ni.prototype.vi=c({Dh:{wi:{type:"boolean",name:"dry_run"},xi:{type:"boolean"},yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","master_node","version"]},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/reroute"},method:"POST"}),e.ni.prototype.state=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/_cluster/state/<%=metric%>/<%=index%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]},index:{type:"list"}}},{Mh:"/_cluster/state/<%=metric%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]}}},{Mh:"/_cluster/state"}]}),e.ni.prototype.Ci=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_cluster/stats/nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cluster/stats"}]}),e.count=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_count",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_count",Nh:{index:{type:"list"}}},{Mh:"/_count"}],method:"POST"}),e.Ni=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.delete=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Si=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Ti=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},method:"DELETE"}),e.Ui=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"HEAD"}),e.xi=c({Dh:{Ii:{type:"boolean",name:"analyze_wildcard"},Hi:{type:"string"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},$h:{type:"list"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},parent:{type:"string"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_explain",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Zi=c({Dh:{$h:{type:"list"},level:{type:"enum",default:"cluster",options:["indices","cluster"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_field_stats",Nh:{index:{type:"list"}}},{Mh:"/_field_stats"}],method:"POST"}),e.get=c({Dh:{$h:{type:"list"},parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.$i=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}}}),e._i=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_source",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.aj=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}}}),e.index=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"string"},type:{type:"string"}}}],Oh:!0,method:"POST"}),e.bi=d(),e.bi.prototype.dj=c({Dh:{Hi:{type:"string"},ej:{type:"list",name:"char_filters"},fj:{type:"string"},filters:{type:"list"},index:{type:"string"},gj:{type:"boolean",name:"prefer_local"},text:{type:"list"},hj:{type:"string"},format:{type:"enum",default:"detailed",options:["detailed","text"]}},Lh:[{Mh:"/<%=index%>/_analyze",Nh:{index:{type:"string"}}},{Mh:"/_analyze"}],method:"POST"}),e.bi.prototype.ij=c({Dh:{jj:{type:"boolean",name:"field_data"},Zh:{type:"boolean"},$h:{type:"list"},ua:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},index:{type:"list"},nj:{type:"boolean"},nl:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_cache/clear",Nh:{index:{type:"list"}}},{Mh:"/_cache/clear"}],method:"POST"}),e.bi.prototype.close=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_close",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.create=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},ol:{type:"boolean",name:"update_all_types"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.delete=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"DELETE"}),e.bi.prototype.pj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ti=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"DELETE"}),e.bi.prototype.rj=c({Dh:{Th:{type:"time",name:"master_timeout"},name:{type:"list"}},url:{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ui=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"HEAD"}),e.bi.prototype.sj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}}],method:"HEAD"}),e.bi.prototype.tj=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"HEAD"}),e.bi.prototype.uj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},method:"HEAD"}),e.bi.prototype.flush=c({Dh:{vj:{type:"boolean"},wj:{type:"boolean",name:"wait_if_ongoing"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush",Nh:{index:{type:"list"}}},{Mh:"/_flush"}],method:"POST"}),e.bi.prototype.xj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush/synced",Nh:{index:{type:"list"}}},{Mh:"/_flush/synced"}],method:"POST"}),e.bi.prototype.get=c({Dh:{Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/<%=feature%>",Nh:{index:{type:"list"},yj:{type:"list",options:["_settings","_mappings","_warmers","_aliases"]}}},{Mh:"/<%=index%>",Nh:{index:{type:"list"}}}]}),e.bi.prototype.zj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}},{Mh:"/_alias"}]}),e.bi.prototype.Aj=c({Dh:{timeout:{type:"time"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_aliases/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_aliases",Nh:{index:{type:"list"}}},{Mh:"/_aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_aliases"}]}),e.bi.prototype.Bj=c({Dh:{Cj:{type:"boolean",name:"include_defaults"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>/field/<%=fields%>",Nh:{index:{type:"list"},type:{type:"list"},$h:{type:"list"}}},{Mh:"/<%=index%>/_mapping/field/<%=fields%>",Nh:{index:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/<%=type%>/field/<%=fields%>",Nh:{type:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/field/<%=fields%>",Nh:{$h:{type:"list"}}}]}),e.bi.prototype.Dj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_mapping",Nh:{index:{type:"list"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"list"}}},{Mh:"/_mapping"}]}),e.bi.prototype.oi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Sh:{type:"boolean"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_settings/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_settings"}]}),e.bi.prototype.aj=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_template/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_template"}]}),e.bi.prototype.Ej=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}]}),e.bi.prototype.Fj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer",Nh:{index:{type:"list"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_warmer"}]}),e.bi.prototype.open=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"closed",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_open",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.Gj=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_optimize",Nh:{index:{type:"list"}}},{Mh:"/_optimize"}],method:"POST"}),e.bi.prototype.Lj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},method:"PUT"}),e.bi.prototype.Mj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},ol:{type:"boolean",name:"update_all_types"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"string"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.ui=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"}},Lh:[{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings"}],Oh:!0,method:"PUT"}),e.bi.prototype.Oj=c({Dh:{order:{type:"number"},create:{type:"boolean",default:!1},timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},Oh:!0,method:"PUT"}),e.bi.prototype.Pj=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"string"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.gi=c({Dh:{Qj:{type:"boolean",default:!1},Rj:{type:"boolean",default:!1,name:"active_only"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_recovery",Nh:{index:{type:"list"}}},{Mh:"/_recovery"}]}),e.bi.prototype.refresh=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},vj:{type:"boolean",default:!1},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_refresh",Nh:{index:{type:"list"}}},{Mh:"/_refresh"}],method:"POST"}),e.bi.prototype.hi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1},Jj:{name:"operation_threading"},ql:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_segments",Nh:{index:{type:"list"}}},{Mh:"/_segments"}]}),e.bi.prototype.rl=c({Dh:{status:{type:"list",options:["green","yellow","red","all"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_shard_stores",Nh:{index:{type:"list"}}},{Mh:"/_shard_stores"}]}),e.bi.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"list"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"indices",options:["cluster","indices","shards"]},types:{type:"list"}},Lh:[{Mh:"/<%=index%>/_stats/<%=metric%>",Nh:{index:{type:"list"},yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/<%=index%>/_stats",Nh:{index:{type:"list"}}},{Mh:"/_stats"}]}),e.bi.prototype.Wj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_aliases"},Oh:!0,method:"POST"}),e.bi.prototype.Xj=c({Dh:{Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},zi:{type:"boolean",name:"ignore_unavailable"},Yj:{type:"boolean",name:"wait_for_completion"},Zj:{type:"boolean",name:"only_ancient_segments"}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}],method:"POST"}),e.bi.prototype.$j=c({Dh:{xi:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},_j:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_validate/query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_validate/query",Nh:{index:{type:"list"}}},{Mh:"/_validate/query"}],method:"POST"}),e.info=c({url:{Mh:"/"}}),e.ak=c({Dh:{$h:{type:"list"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mget",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mget",Nh:{index:{type:"string"}}},{Mh:"/_mget"}],Oh:!0,method:"POST"}),e.uk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mpercolate",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mpercolate",Nh:{index:{type:"string"}}},{Mh:"/_mpercolate"}],Oh:!0,Ph:!0,method:"POST"}),e.vk=c({Dh:{rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_msearch",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_msearch",Nh:{index:{type:"list"}}},{Mh:"/_msearch"}],Oh:!0,Ph:!0,method:"POST"}),e.wk=c({Dh:{xk:{type:"list",required:!1},yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mtermvectors",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mtermvectors",Nh:{index:{type:"string"}}},{Mh:"/_mtermvectors"}],method:"POST"}),e.ei=d(),e.ei.prototype.Dk=c({Dh:{interval:{type:"time"},Ek:{type:"number"},Fk:{type:"number"},Gk:{type:"boolean",name:"ignore_idle_threads"},type:{type:"enum",options:["cpu","wait","block"]},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/hotthreads",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/hotthreads"}]}),e.ei.prototype.info=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/<%=metric%>",Nh:{yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes"}]}),e.ei.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"boolean"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"node",options:["node","indices","shards"]},types:{type:"list"},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats/<%=metric%>/<%=indexMetric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats"}]}),e.Kk=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},Mk:{type:"string",name:"percolate_routing"},Nk:{type:"string",name:"percolate_preference"},Lk:{type:"enum",options:["ids"],name:"percolate_format"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.ping=c({url:{Mh:"/"},Ok:3e3,method:"HEAD"}),e.Pk=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},Oh:!0,method:"PUT"}),e.Oj=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},Oh:!0,method:"PUT"}),e.sl=c({Lh:[{Mh:"/_render/template/<%=id%>",Nh:{id:{type:"string"}}},{Mh:"/_render/template"}],method:"POST"}),e.scroll=c({Dh:{scroll:{type:"duration"},mi:{type:"string",name:"scroll_id"}},Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"string"}}},{Mh:"/_search/scroll"}],Qk:"scrollId",method:"POST"}),e.search=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","dfs_query_then_fetch","count","scan"],name:"search_type"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},tl:{type:"number",name:"terminate_after"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search",Nh:{index:{type:"list"}}},{Mh:"/_search"}],method:"POST"}),e.Wk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/exists",
Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/exists",Nh:{index:{type:"list"}}},{Mh:"/_search/exists"}],method:"POST"}),e.Xk=c({Dh:{Fi:{type:"string"},Kh:{type:"string"},Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search_shards",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search_shards",Nh:{index:{type:"list"}}},{Mh:"/_search_shards"}],method:"POST"}),e.Yk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/template",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/template",Nh:{index:{type:"list"}}},{Mh:"/_search/template"}],method:"POST"}),e.Vj=d(),e.Vj.prototype.create=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.$k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},verify:{type:"boolean"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"string"}}},Oh:!0,method:"POST"}),e.Vj.prototype.delete=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"DELETE"}),e.Vj.prototype._k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},method:"DELETE"}),e.Vj.prototype.get=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"list"}}}}),e.Vj.prototype.al=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},{Mh:"/_snapshot"}]}),e.Vj.prototype.restore=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_restore",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.status=c({Dh:{Th:{type:"time",name:"master_timeout"}},Lh:[{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_status",Nh:{Zk:{type:"string"},Vj:{type:"list"}}},{Mh:"/_snapshot/<%=repository%>/_status",Nh:{Zk:{type:"string"}}},{Mh:"/_snapshot/_status"}]}),e.Vj.prototype.bl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>/_verify",Nh:{Zk:{type:"string"}}},method:"POST"}),e.cl=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"string"}},Lh:[{Mh:"/<%=index%>/_suggest",Nh:{index:{type:"list"}}},{Mh:"/_suggest"}],Oh:!0,method:"POST"}),e.ul=c({Dh:{yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},vl:{type:"boolean",default:!1,required:!1},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.update=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},$h:{type:"list"},lang:{type:"string"},parent:{type:"string"},refresh:{type:"boolean"},el:{type:"number",name:"retry_on_conflict"},Kh:{type:"string"},fl:{},gl:{name:"script_id"},hl:{type:"boolean",name:"scripted_upsert"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_update",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.create=c.il(e.index,{transform:function(a){a.jl="create"}})},{kl:29,ll:50}],22:[function(a,b){var c=a("../client_action").Ch(function(b){return a("../utils").Hd(b,{Dh:{Eh:{type:"list",name:"filter_path"}}})}),d=a("../client_action").Fh,e=b.g={};e.Gh=["cat","cluster","indices","nodes","snapshot"],e.Hh=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},type:{type:"string"},$h:{type:"list"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_bulk",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_bulk",Nh:{index:{type:"string"}}},{Mh:"/_bulk"}],Oh:!0,Ph:!0,method:"POST"}),e.Qh=d(),e.Qh.prototype.Rh=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_cat/aliases"}]}),e.Qh.prototype.Wh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/allocation/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cat/allocation"}]}),e.Qh.prototype.count=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/count/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/count"}]}),e.Qh.prototype.Zh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},$h:{type:"list"}},Lh:[{Mh:"/_cat/fielddata/<%=fields%>",Nh:{$h:{type:"list"}}},{Mh:"/_cat/fielddata"}]}),e.Qh.prototype._h=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ai:{type:"boolean",default:!0},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/health"}}),e.Qh.prototype.Vh=c({Dh:{Vh:{type:"boolean",default:!1}},url:{Mh:"/_cat"}}),e.Qh.prototype.bi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ci:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/indices/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/indices"}]}),e.Qh.prototype.di=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/master"}}),e.Qh.prototype.ml=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodeattrs"}}),e.Qh.prototype.ei=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodes"}}),e.Qh.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/pending_tasks"}}),e.Qh.prototype.plugins=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/plugins"}}),e.Qh.prototype.gi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/recovery/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/recovery"}]}),e.Qh.prototype.wl=c({Dh:{Sh:{type:"boolean",default:!1},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/repositories"}}),e.Qh.prototype.hi=c({Dh:{Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/segments/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/segments"}]}),e.Qh.prototype.ii=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/shards/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/shards"}]}),e.Qh.prototype.Ek=c({Dh:{Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/snapshots/<%=repository%>",Nh:{Zk:{type:"list"}}}}),e.Qh.prototype.ji=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},ki:{type:"boolean",default:!1,name:"full_id"}},url:{Mh:"/_cat/thread_pool"}}),e.li=c({Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"list"}}},{Mh:"/_search/scroll"}],method:"DELETE"}),e.ni=d(),e.ni.prototype.oi=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"}}),e.ni.prototype._h=c({Dh:{level:{type:"enum",default:"cluster",options:["cluster","indices","shards"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},qi:{type:"number",name:"wait_for_active_shards"},ri:{type:"string",name:"wait_for_nodes"},si:{type:"number",name:"wait_for_relocating_shards"},ti:{type:"enum",default:null,options:["green","yellow","red"],name:"wait_for_status"}},Lh:[{Mh:"/_cluster/health/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cluster/health"}]}),e.ni.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_cluster/pending_tasks"}}),e.ni.prototype.ui=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"},method:"PUT"}),e.ni.prototype.vi=c({Dh:{wi:{type:"boolean",name:"dry_run"},xi:{type:"boolean"},yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","master_node","version"]},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/reroute"},method:"POST"}),e.ni.prototype.state=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/_cluster/state/<%=metric%>/<%=index%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]},index:{type:"list"}}},{Mh:"/_cluster/state/<%=metric%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]}}},{Mh:"/_cluster/state"}]}),e.ni.prototype.Ci=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_cluster/stats/nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cluster/stats"}]}),e.count=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_count",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_count",Nh:{index:{type:"list"}}},{Mh:"/_count"}],method:"POST"}),e.Ni=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.delete=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Si=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Ti=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},method:"DELETE"}),e.Ui=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"HEAD"}),e.xi=c({Dh:{Ii:{type:"boolean",name:"analyze_wildcard"},Hi:{type:"string"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},$h:{type:"list"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},parent:{type:"string"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_explain",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Zi=c({Dh:{$h:{type:"list"},level:{type:"enum",default:"cluster",options:["indices","cluster"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_field_stats",Nh:{index:{type:"list"}}},{Mh:"/_field_stats"}],method:"POST"}),e.get=c({Dh:{$h:{type:"list"},parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.$i=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}}}),e._i=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_source",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.aj=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}}}),e.index=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"string"},type:{type:"string"}}}],Oh:!0,method:"POST"}),e.bi=d(),e.bi.prototype.dj=c({Dh:{Hi:{type:"string"},ej:{type:"list",name:"char_filters"},fj:{type:"string"},filters:{type:"list"},index:{type:"string"},gj:{type:"boolean",name:"prefer_local"},text:{type:"list"},hj:{type:"string"},format:{type:"enum",default:"detailed",options:["detailed","text"]}},Lh:[{Mh:"/<%=index%>/_analyze",Nh:{index:{type:"string"}}},{Mh:"/_analyze"}],method:"POST"}),e.bi.prototype.ij=c({Dh:{jj:{type:"boolean",name:"field_data"},Zh:{type:"boolean"},$h:{type:"list"},ua:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},index:{type:"list"},nj:{type:"boolean"},nl:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_cache/clear",Nh:{index:{type:"list"}}},{Mh:"/_cache/clear"}],method:"POST"}),e.bi.prototype.close=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_close",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.create=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},ol:{type:"boolean",name:"update_all_types"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.delete=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"DELETE"}),e.bi.prototype.pj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ti=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"DELETE"}),e.bi.prototype.rj=c({Dh:{Th:{type:"time",name:"master_timeout"},name:{type:"list"}},url:{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ui=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"HEAD"}),e.bi.prototype.sj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}}],method:"HEAD"}),e.bi.prototype.tj=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"HEAD"}),e.bi.prototype.uj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},method:"HEAD"}),e.bi.prototype.flush=c({Dh:{vj:{type:"boolean"},wj:{type:"boolean",name:"wait_if_ongoing"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush",Nh:{index:{type:"list"}}},{Mh:"/_flush"}],method:"POST"}),e.bi.prototype.xj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush/synced",Nh:{index:{type:"list"}}},{Mh:"/_flush/synced"}],method:"POST"}),e.bi.prototype.xl=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_forcemerge",Nh:{index:{type:"list"}}},{Mh:"/_forcemerge"}],method:"POST"}),e.bi.prototype.get=c({Dh:{Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/<%=feature%>",Nh:{index:{type:"list"},yj:{type:"list",options:["_settings","_mappings","_warmers","_aliases"]}}},{Mh:"/<%=index%>",Nh:{index:{type:"list"}}}]}),e.bi.prototype.zj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}},{Mh:"/_alias"}]}),e.bi.prototype.Aj=c({Dh:{timeout:{type:"time"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_aliases/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_aliases",Nh:{index:{type:"list"}}},{Mh:"/_aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_aliases"}]}),e.bi.prototype.Bj=c({Dh:{Cj:{type:"boolean",name:"include_defaults"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>/field/<%=fields%>",Nh:{index:{type:"list"},type:{type:"list"},$h:{type:"list"}}},{Mh:"/<%=index%>/_mapping/field/<%=fields%>",Nh:{index:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/<%=type%>/field/<%=fields%>",Nh:{type:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/field/<%=fields%>",Nh:{$h:{type:"list"}}}]}),e.bi.prototype.Dj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_mapping",Nh:{index:{type:"list"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"list"}}},{Mh:"/_mapping"}]}),e.bi.prototype.oi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Sh:{type:"boolean"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_settings/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_settings"}]}),e.bi.prototype.aj=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_template/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_template"}]}),e.bi.prototype.Ej=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}]}),e.bi.prototype.Fj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer",Nh:{index:{type:"list"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_warmer"}]}),e.bi.prototype.open=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"closed",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_open",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.Gj=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_optimize",Nh:{index:{type:"list"}}},{Mh:"/_optimize"}],method:"POST"}),e.bi.prototype.Lj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},method:"PUT"}),e.bi.prototype.Mj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},ol:{type:"boolean",name:"update_all_types"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"string"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.ui=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"}},Lh:[{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings"}],Oh:!0,method:"PUT"}),e.bi.prototype.Oj=c({Dh:{order:{type:"number"},create:{type:"boolean",default:!1},timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},Oh:!0,method:"PUT"}),e.bi.prototype.Pj=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"string"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.gi=c({Dh:{Qj:{type:"boolean",default:!1},Rj:{type:"boolean",default:!1,name:"active_only"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_recovery",Nh:{index:{type:"list"}}},{Mh:"/_recovery"}]}),e.bi.prototype.refresh=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},vj:{type:"boolean",default:!1},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_refresh",Nh:{index:{type:"list"}}},{Mh:"/_refresh"}],method:"POST"}),e.bi.prototype.hi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1},Jj:{name:"operation_threading"},ql:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_segments",Nh:{index:{type:"list"}}},{Mh:"/_segments"}]}),e.bi.prototype.rl=c({Dh:{status:{type:"list",options:["green","yellow","red","all"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_shard_stores",Nh:{index:{type:"list"}}},{Mh:"/_shard_stores"}]}),e.bi.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"list"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"indices",options:["cluster","indices","shards"]},types:{type:"list"}},Lh:[{Mh:"/<%=index%>/_stats/<%=metric%>",Nh:{index:{type:"list"},yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/<%=index%>/_stats",Nh:{index:{type:"list"}}},{Mh:"/_stats"}]}),e.bi.prototype.Wj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_aliases"},Oh:!0,method:"POST"}),e.bi.prototype.Xj=c({Dh:{Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},zi:{type:"boolean",name:"ignore_unavailable"},Yj:{type:"boolean",name:"wait_for_completion"},Zj:{type:"boolean",name:"only_ancient_segments"}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}],method:"POST"}),e.bi.prototype.$j=c({Dh:{xi:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},_j:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_validate/query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_validate/query",Nh:{index:{type:"list"}}},{Mh:"/_validate/query"}],method:"POST"}),e.info=c({url:{Mh:"/"}}),e.ak=c({Dh:{$h:{type:"list"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mget",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mget",Nh:{index:{type:"string"}}},{Mh:"/_mget"}],Oh:!0,method:"POST"}),e.uk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",
name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mpercolate",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mpercolate",Nh:{index:{type:"string"}}},{Mh:"/_mpercolate"}],Oh:!0,Ph:!0,method:"POST"}),e.vk=c({Dh:{rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_msearch",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_msearch",Nh:{index:{type:"list"}}},{Mh:"/_msearch"}],Oh:!0,Ph:!0,method:"POST"}),e.wk=c({Dh:{xk:{type:"list",required:!1},yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mtermvectors",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mtermvectors",Nh:{index:{type:"string"}}},{Mh:"/_mtermvectors"}],method:"POST"}),e.ei=d(),e.ei.prototype.Dk=c({Dh:{interval:{type:"time"},Ek:{type:"number"},Fk:{type:"number"},Gk:{type:"boolean",name:"ignore_idle_threads"},type:{type:"enum",options:["cpu","wait","block"]},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/hotthreads",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/hotthreads"}]}),e.ei.prototype.info=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/<%=metric%>",Nh:{yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes"}]}),e.ei.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"boolean"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"node",options:["node","indices","shards"]},types:{type:"list"},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats/<%=metric%>/<%=indexMetric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats"}]}),e.Kk=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},Mk:{type:"string",name:"percolate_routing"},Nk:{type:"string",name:"percolate_preference"},Lk:{type:"enum",options:["ids"],name:"percolate_format"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.ping=c({url:{Mh:"/"},Ok:3e3,method:"HEAD"}),e.Pk=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},Oh:!0,method:"PUT"}),e.Oj=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},Oh:!0,method:"PUT"}),e.sl=c({Lh:[{Mh:"/_render/template/<%=id%>",Nh:{id:{type:"string"}}},{Mh:"/_render/template"}],method:"POST"}),e.scroll=c({Dh:{scroll:{type:"duration"},mi:{type:"string",name:"scroll_id"}},Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"string"}}},{Mh:"/_search/scroll"}],Qk:"scrollId",method:"POST"}),e.search=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","dfs_query_then_fetch","count","scan"],name:"search_type"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},tl:{type:"number",name:"terminate_after"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search",Nh:{index:{type:"list"}}},{Mh:"/_search"}],method:"POST"}),e.Wk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/exists",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/exists",Nh:{index:{type:"list"}}},{Mh:"/_search/exists"}],method:"POST"}),e.Xk=c({Dh:{Fi:{type:"string"},Kh:{type:"string"},Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search_shards",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search_shards",Nh:{index:{type:"list"}}},{Mh:"/_search_shards"}],method:"POST"}),e.Yk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/template",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/template",Nh:{index:{type:"list"}}},{Mh:"/_search/template"}],method:"POST"}),e.Vj=d(),e.Vj.prototype.create=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.$k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},verify:{type:"boolean"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"string"}}},Oh:!0,method:"POST"}),e.Vj.prototype.delete=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"DELETE"}),e.Vj.prototype._k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},method:"DELETE"}),e.Vj.prototype.get=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"list"}}}}),e.Vj.prototype.al=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},{Mh:"/_snapshot"}]}),e.Vj.prototype.restore=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_restore",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.status=c({Dh:{Th:{type:"time",name:"master_timeout"}},Lh:[{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_status",Nh:{Zk:{type:"string"},Vj:{type:"list"}}},{Mh:"/_snapshot/<%=repository%>/_status",Nh:{Zk:{type:"string"}}},{Mh:"/_snapshot/_status"}]}),e.Vj.prototype.bl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>/_verify",Nh:{Zk:{type:"string"}}},method:"POST"}),e.cl=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"string"}},Lh:[{Mh:"/<%=index%>/_suggest",Nh:{index:{type:"list"}}},{Mh:"/_suggest"}],Oh:!0,method:"POST"}),e.ul=c({Dh:{yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},vl:{type:"boolean",default:!1,required:!1},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.update=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},$h:{type:"list"},lang:{type:"string"},parent:{type:"string"},refresh:{type:"boolean"},el:{type:"number",name:"retry_on_conflict"},Kh:{type:"string"},fl:{},gl:{name:"script_id"},hl:{type:"boolean",name:"scripted_upsert"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_update",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.create=c.il(e.index,{transform:function(a){a.jl="create"}})},{kl:29,ll:50}],23:[function(a,b){var c=a("../client_action").Ch(function(b){return a("../utils").Hd(b,{Dh:{Eh:{type:"list",name:"filter_path"}}})}),d=a("../client_action").Fh,e=b.g={};e.Gh=["cat","cluster","indices","nodes","snapshot"],e.Hh=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},type:{type:"string"},$h:{type:"list"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_bulk",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_bulk",Nh:{index:{type:"string"}}},{Mh:"/_bulk"}],Oh:!0,Ph:!0,method:"POST"}),e.Qh=d(),e.Qh.prototype.Rh=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_cat/aliases"}]}),e.Qh.prototype.Wh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/allocation/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cat/allocation"}]}),e.Qh.prototype.count=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/count/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/count"}]}),e.Qh.prototype.Zh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},$h:{type:"list"}},Lh:[{Mh:"/_cat/fielddata/<%=fields%>",Nh:{$h:{type:"list"}}},{Mh:"/_cat/fielddata"}]}),e.Qh.prototype._h=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ai:{type:"boolean",default:!0},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/health"}}),e.Qh.prototype.Vh=c({Dh:{Vh:{type:"boolean",default:!1}},url:{Mh:"/_cat"}}),e.Qh.prototype.bi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ci:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/indices/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/indices"}]}),e.Qh.prototype.di=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/master"}}),e.Qh.prototype.ml=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodeattrs"}}),e.Qh.prototype.ei=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodes"}}),e.Qh.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/pending_tasks"}}),e.Qh.prototype.plugins=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/plugins"}}),e.Qh.prototype.gi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/recovery/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/recovery"}]}),e.Qh.prototype.wl=c({Dh:{Sh:{type:"boolean",default:!1},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/repositories"}}),e.Qh.prototype.hi=c({Dh:{Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/segments/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/segments"}]}),e.Qh.prototype.ii=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/shards/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/shards"}]}),e.Qh.prototype.Ek=c({Dh:{zi:{type:"boolean",default:!1,name:"ignore_unavailable"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/snapshots/<%=repository%>",Nh:{Zk:{type:"list"}}}}),e.Qh.prototype.ji=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},ki:{type:"boolean",default:!1,name:"full_id"}},url:{Mh:"/_cat/thread_pool"}}),e.li=c({Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"list"}}},{Mh:"/_search/scroll"}],method:"DELETE"}),e.ni=d(),e.ni.prototype.oi=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"}}),e.ni.prototype._h=c({Dh:{level:{type:"enum",default:"cluster",options:["cluster","indices","shards"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},qi:{type:"number",name:"wait_for_active_shards"},ri:{type:"string",name:"wait_for_nodes"},si:{type:"number",name:"wait_for_relocating_shards"},ti:{type:"enum",default:null,options:["green","yellow","red"],name:"wait_for_status"}},Lh:[{Mh:"/_cluster/health/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cluster/health"}]}),e.ni.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_cluster/pending_tasks"}}),e.ni.prototype.ui=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"},method:"PUT"}),e.ni.prototype.vi=c({Dh:{wi:{type:"boolean",name:"dry_run"},xi:{type:"boolean"},yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","master_node","version"]},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/reroute"},method:"POST"}),e.ni.prototype.state=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/_cluster/state/<%=metric%>/<%=index%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]},index:{type:"list"}}},{Mh:"/_cluster/state/<%=metric%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]}}},{Mh:"/_cluster/state"}]}),e.ni.prototype.Ci=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_cluster/stats/nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cluster/stats"}]}),e.count=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_count",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_count",Nh:{index:{type:"list"}}},{Mh:"/_count"}],method:"POST"}),e.Ni=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.delete=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Si=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Ti=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},method:"DELETE"}),e.Ui=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"HEAD"}),e.xi=c({Dh:{Ii:{type:"boolean",name:"analyze_wildcard"},Hi:{type:"string"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},$h:{type:"list"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},parent:{type:"string"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_explain",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Zi=c({Dh:{$h:{type:"list"},level:{type:"enum",default:"cluster",options:["indices","cluster"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_field_stats",Nh:{index:{type:"list"}}},{Mh:"/_field_stats"}],method:"POST"}),e.get=c({Dh:{$h:{type:"list"},parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.$i=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}}}),e._i=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_source",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.aj=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}}}),e.index=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"string"},type:{type:"string"}}}],Oh:!0,method:"POST"}),e.bi=d(),e.bi.prototype.dj=c({Dh:{Hi:{type:"string"},ej:{type:"list",name:"char_filters"},fj:{type:"string"},filters:{type:"list"},index:{type:"string"},gj:{type:"boolean",name:"prefer_local"},text:{type:"list"},hj:{type:"string"},detail:{type:"boolean"},attributes:{type:"list"},format:{type:"enum",default:"detailed",options:["detailed","text"]}},Lh:[{Mh:"/<%=index%>/_analyze",Nh:{index:{type:"string"}}},{Mh:"/_analyze"}],method:"POST"}),e.bi.prototype.ij=c({Dh:{jj:{type:"boolean",name:"field_data"},Zh:{type:"boolean"},$h:{type:"list"},ua:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},index:{type:"list"},nj:{type:"boolean"},nl:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_cache/clear",Nh:{index:{type:"list"}}},{Mh:"/_cache/clear"}],method:"POST"}),e.bi.prototype.close=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_close",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.create=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},ol:{type:"boolean",name:"update_all_types"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.delete=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"DELETE"}),e.bi.prototype.pj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ti=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"DELETE"}),e.bi.prototype.rj=c({Dh:{Th:{type:"time",name:"master_timeout"},name:{type:"list"}},url:{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ui=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"HEAD"}),e.bi.prototype.sj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}}],method:"HEAD"}),e.bi.prototype.tj=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"HEAD"}),e.bi.prototype.uj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},method:"HEAD"}),e.bi.prototype.flush=c({Dh:{vj:{type:"boolean"},wj:{type:"boolean",name:"wait_if_ongoing"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush",Nh:{index:{type:"list"}}},{Mh:"/_flush"}],method:"POST"}),e.bi.prototype.xj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush/synced",Nh:{index:{type:"list"}}},{Mh:"/_flush/synced"}],method:"POST"}),e.bi.prototype.xl=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_forcemerge",Nh:{index:{type:"list"}}},{Mh:"/_forcemerge"}],method:"POST"}),e.bi.prototype.get=c({Dh:{Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/<%=feature%>",Nh:{index:{type:"list"},yj:{type:"list",options:["_settings","_mappings","_warmers","_aliases"]}}},{Mh:"/<%=index%>",Nh:{index:{type:"list"}}}]}),e.bi.prototype.zj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}},{Mh:"/_alias"}]}),e.bi.prototype.Aj=c({Dh:{timeout:{type:"time"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_aliases/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_aliases",Nh:{index:{type:"list"}}},{Mh:"/_aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_aliases"}]}),e.bi.prototype.Bj=c({Dh:{Cj:{type:"boolean",name:"include_defaults"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>/field/<%=fields%>",Nh:{index:{type:"list"},type:{type:"list"},$h:{type:"list"}}},{Mh:"/<%=index%>/_mapping/field/<%=fields%>",Nh:{index:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/<%=type%>/field/<%=fields%>",Nh:{type:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/field/<%=fields%>",Nh:{$h:{type:"list"}}}]}),e.bi.prototype.Dj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_mapping",Nh:{index:{type:"list"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"list"}}},{Mh:"/_mapping"}]}),e.bi.prototype.oi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Sh:{type:"boolean"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_settings/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_settings"}]}),e.bi.prototype.aj=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_template/<%=name%>",Nh:{name:{
type:"list"}}},{Mh:"/_template"}]}),e.bi.prototype.Ej=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}]}),e.bi.prototype.Fj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer",Nh:{index:{type:"list"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_warmer"}]}),e.bi.prototype.open=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"closed",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_open",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.Gj=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_optimize",Nh:{index:{type:"list"}}},{Mh:"/_optimize"}],method:"POST"}),e.bi.prototype.Lj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},method:"PUT"}),e.bi.prototype.Mj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},ol:{type:"boolean",name:"update_all_types"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"string"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.ui=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"}},Lh:[{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings"}],Oh:!0,method:"PUT"}),e.bi.prototype.Oj=c({Dh:{order:{type:"number"},create:{type:"boolean",default:!1},timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},Oh:!0,method:"PUT"}),e.bi.prototype.Pj=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"string"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.gi=c({Dh:{Qj:{type:"boolean",default:!1},Rj:{type:"boolean",default:!1,name:"active_only"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_recovery",Nh:{index:{type:"list"}}},{Mh:"/_recovery"}]}),e.bi.prototype.refresh=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},vj:{type:"boolean",default:!1},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_refresh",Nh:{index:{type:"list"}}},{Mh:"/_refresh"}],method:"POST"}),e.bi.prototype.hi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1},Jj:{name:"operation_threading"},ql:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_segments",Nh:{index:{type:"list"}}},{Mh:"/_segments"}]}),e.bi.prototype.rl=c({Dh:{status:{type:"list",options:["green","yellow","red","all"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_shard_stores",Nh:{index:{type:"list"}}},{Mh:"/_shard_stores"}]}),e.bi.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"list"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"indices",options:["cluster","indices","shards"]},types:{type:"list"}},Lh:[{Mh:"/<%=index%>/_stats/<%=metric%>",Nh:{index:{type:"list"},yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/<%=index%>/_stats",Nh:{index:{type:"list"}}},{Mh:"/_stats"}]}),e.bi.prototype.Wj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_aliases"},Oh:!0,method:"POST"}),e.bi.prototype.Xj=c({Dh:{Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},zi:{type:"boolean",name:"ignore_unavailable"},Yj:{type:"boolean",name:"wait_for_completion"},Zj:{type:"boolean",name:"only_ancient_segments"}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}],method:"POST"}),e.bi.prototype.$j=c({Dh:{xi:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},_j:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_validate/query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_validate/query",Nh:{index:{type:"list"}}},{Mh:"/_validate/query"}],method:"POST"}),e.info=c({url:{Mh:"/"}}),e.ak=c({Dh:{$h:{type:"list"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mget",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mget",Nh:{index:{type:"string"}}},{Mh:"/_mget"}],Oh:!0,method:"POST"}),e.uk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mpercolate",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mpercolate",Nh:{index:{type:"string"}}},{Mh:"/_mpercolate"}],Oh:!0,Ph:!0,method:"POST"}),e.vk=c({Dh:{rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_msearch",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_msearch",Nh:{index:{type:"list"}}},{Mh:"/_msearch"}],Oh:!0,Ph:!0,method:"POST"}),e.wk=c({Dh:{xk:{type:"list",required:!1},yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mtermvectors",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mtermvectors",Nh:{index:{type:"string"}}},{Mh:"/_mtermvectors"}],method:"POST"}),e.ei=d(),e.ei.prototype.Dk=c({Dh:{interval:{type:"time"},Ek:{type:"number"},Fk:{type:"number"},Gk:{type:"boolean",name:"ignore_idle_threads"},type:{type:"enum",options:["cpu","wait","block"]},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/hotthreads",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/hotthreads"}]}),e.ei.prototype.info=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/<%=metric%>",Nh:{yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes"}]}),e.ei.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"boolean"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"node",options:["node","indices","shards"]},types:{type:"list"},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats/<%=metric%>/<%=indexMetric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats"}]}),e.Kk=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},Mk:{type:"string",name:"percolate_routing"},Nk:{type:"string",name:"percolate_preference"},Lk:{type:"enum",options:["ids"],name:"percolate_format"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.ping=c({url:{Mh:"/"},Ok:3e3,method:"HEAD"}),e.Pk=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},Oh:!0,method:"PUT"}),e.Oj=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},Oh:!0,method:"PUT"}),e.sl=c({Lh:[{Mh:"/_render/template/<%=id%>",Nh:{id:{type:"string"}}},{Mh:"/_render/template"}],method:"POST"}),e.scroll=c({Dh:{scroll:{type:"duration"},mi:{type:"string",name:"scroll_id"}},Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"string"}}},{Mh:"/_search/scroll"}],Qk:"scrollId",method:"POST"}),e.search=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","dfs_query_then_fetch","count","scan"],name:"search_type"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},tl:{type:"number",name:"terminate_after"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search",Nh:{index:{type:"list"}}},{Mh:"/_search"}],method:"POST"}),e.Wk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/exists",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/exists",Nh:{index:{type:"list"}}},{Mh:"/_search/exists"}],method:"POST"}),e.Xk=c({Dh:{Fi:{type:"string"},Kh:{type:"string"},Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search_shards",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search_shards",Nh:{index:{type:"list"}}},{Mh:"/_search_shards"}],method:"POST"}),e.Yk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/template",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/template",Nh:{index:{type:"list"}}},{Mh:"/_search/template"}],method:"POST"}),e.Vj=d(),e.Vj.prototype.create=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.$k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},verify:{type:"boolean"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"string"}}},Oh:!0,method:"POST"}),e.Vj.prototype.delete=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"DELETE"}),e.Vj.prototype._k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},method:"DELETE"}),e.Vj.prototype.get=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"list"}}}}),e.Vj.prototype.al=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},{Mh:"/_snapshot"}]}),e.Vj.prototype.restore=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_restore",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.status=c({Dh:{Th:{type:"time",name:"master_timeout"}},Lh:[{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_status",Nh:{Zk:{type:"string"},Vj:{type:"list"}}},{Mh:"/_snapshot/<%=repository%>/_status",Nh:{Zk:{type:"string"}}},{Mh:"/_snapshot/_status"}]}),e.Vj.prototype.bl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>/_verify",Nh:{Zk:{type:"string"}}},method:"POST"}),e.cl=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"string"}},Lh:[{Mh:"/<%=index%>/_suggest",Nh:{index:{type:"list"}}},{Mh:"/_suggest"}],Oh:!0,method:"POST"}),e.ul=c({Dh:{yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},vl:{type:"boolean",default:!1,required:!1},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.update=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},$h:{type:"list"},lang:{type:"string"},parent:{type:"string"},refresh:{type:"boolean"},el:{type:"number",name:"retry_on_conflict"},Kh:{type:"string"},fl:{},gl:{name:"script_id"},hl:{type:"boolean",name:"scripted_upsert"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_update",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.create=c.il(e.index,{transform:function(a){a.jl="create"}})},{kl:29,ll:50}],24:[function(a,b){var c=a("../client_action").Ch(function(b){return a("../utils").Hd(b,{Dh:{Eh:{type:"list",name:"filter_path"}}})}),d=a("../client_action").Fh,e=b.g={};e.Gh=["cat","cluster","indices","nodes","snapshot","tasks"],e.Hh=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},type:{type:"string"},$h:{type:"list"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_bulk",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_bulk",Nh:{index:{type:"string"}}},{Mh:"/_bulk"}],Oh:!0,Ph:!0,method:"POST"}),e.Qh=d(),e.Qh.prototype.Rh=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_cat/aliases"}]}),e.Qh.prototype.Wh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/allocation/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cat/allocation"}]}),e.Qh.prototype.count=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/count/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/count"}]}),e.Qh.prototype.Zh=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},$h:{type:"list"}},Lh:[{Mh:"/_cat/fielddata/<%=fields%>",Nh:{$h:{type:"list"}}},{Mh:"/_cat/fielddata"}]}),e.Qh.prototype._h=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ai:{type:"boolean",default:!0},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/health"}}),e.Qh.prototype.Vh=c({Dh:{Vh:{type:"boolean",default:!1}},url:{Mh:"/_cat"}}),e.Qh.prototype.bi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ci:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/indices/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/indices"}]}),e.Qh.prototype.di=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/master"}}),e.Qh.prototype.ml=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodeattrs"}}),e.Qh.prototype.ei=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodes"}}),e.Qh.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/pending_tasks"}}),e.Qh.prototype.plugins=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/plugins"}}),e.Qh.prototype.gi=c({Dh:{Xh:{type:"enum",options:["b","k","m","g"]},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/recovery/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/recovery"}]}),e.Qh.prototype.wl=c({Dh:{Sh:{type:"boolean",default:!1},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/repositories"}}),e.Qh.prototype.hi=c({Dh:{Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/segments/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/segments"}]}),e.Qh.prototype.ii=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/shards/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/shards"}]}),e.Qh.prototype.Ek=c({Dh:{zi:{type:"boolean",default:!1,name:"ignore_unavailable"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/snapshots/<%=repository%>",Nh:{Zk:{type:"list"}}}}),e.Qh.prototype.ji=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},ki:{type:"boolean",default:!1,name:"full_id"}},url:{Mh:"/_cat/thread_pool"}}),e.li=c({Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"list"}}},{Mh:"/_search/scroll"}],method:"DELETE"}),e.ni=d(),e.ni.prototype.oi=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"}}),e.ni.prototype._h=c({Dh:{level:{type:"enum",default:"cluster",options:["cluster","indices","shards"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},qi:{type:"number",name:"wait_for_active_shards"},ri:{type:"string",name:"wait_for_nodes"},si:{type:"number",name:"wait_for_relocating_shards"},ti:{type:"enum",default:null,options:["green","yellow","red"],name:"wait_for_status"}},Lh:[{Mh:"/_cluster/health/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cluster/health"}]}),e.ni.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_cluster/pending_tasks"}}),e.ni.prototype.ui=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"},method:"PUT"}),e.ni.prototype.vi=c({Dh:{wi:{type:"boolean",name:"dry_run"},xi:{type:"boolean"},yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","master_node","version"]},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/reroute"},method:"POST"}),e.ni.prototype.state=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/_cluster/state/<%=metric%>/<%=index%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]},index:{type:"list"}}},{Mh:"/_cluster/state/<%=metric%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]}}},{Mh:"/_cluster/state"}]}),e.ni.prototype.Ci=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_cluster/stats/nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cluster/stats"}]}),e.count=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_count",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_count",Nh:{index:{type:"list"}}},{Mh:"/_count"}],method:"POST"}),e.Ni=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.delete=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Si=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Ti=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},method:"DELETE"}),e.Ui=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"HEAD"}),e.xi=c({Dh:{Ii:{type:"boolean",name:"analyze_wildcard"},Hi:{type:"string"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},$h:{type:"list"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},parent:{type:"string"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_explain",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Zi=c({Dh:{$h:{type:"list"},level:{type:"enum",default:"cluster",options:["indices","cluster"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_field_stats",Nh:{index:{type:"list"}}},{Mh:"/_field_stats"}],method:"POST"}),e.get=c({Dh:{$h:{type:"list"},parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.$i=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}}}),e._i=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_source",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.aj=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}}}),e.index=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"string"
},type:{type:"string"}}}],Oh:!0,method:"POST"}),e.bi=d(),e.bi.prototype.dj=c({Dh:{Hi:{type:"string"},ej:{type:"list",name:"char_filters"},fj:{type:"string"},filters:{type:"list"},index:{type:"string"},gj:{type:"boolean",name:"prefer_local"},text:{type:"list"},hj:{type:"string"},xi:{type:"boolean"},attributes:{type:"list"},format:{type:"enum",default:"detailed",options:["detailed","text"]}},Lh:[{Mh:"/<%=index%>/_analyze",Nh:{index:{type:"string"}}},{Mh:"/_analyze"}],method:"POST"}),e.bi.prototype.ij=c({Dh:{jj:{type:"boolean",name:"field_data"},Zh:{type:"boolean"},$h:{type:"list"},ua:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},index:{type:"list"},nj:{type:"boolean"},nl:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_cache/clear",Nh:{index:{type:"list"}}},{Mh:"/_cache/clear"}],method:"POST"}),e.bi.prototype.close=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_close",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.create=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},ol:{type:"boolean",name:"update_all_types"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.delete=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"DELETE"}),e.bi.prototype.pj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ti=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"DELETE"}),e.bi.prototype.rj=c({Dh:{Th:{type:"time",name:"master_timeout"},name:{type:"list"}},url:{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ui=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"HEAD"}),e.bi.prototype.sj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}}],method:"HEAD"}),e.bi.prototype.tj=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"HEAD"}),e.bi.prototype.uj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},method:"HEAD"}),e.bi.prototype.flush=c({Dh:{vj:{type:"boolean"},wj:{type:"boolean",name:"wait_if_ongoing"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush",Nh:{index:{type:"list"}}},{Mh:"/_flush"}],method:"POST"}),e.bi.prototype.xj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush/synced",Nh:{index:{type:"list"}}},{Mh:"/_flush/synced"}],method:"POST"}),e.bi.prototype.xl=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_forcemerge",Nh:{index:{type:"list"}}},{Mh:"/_forcemerge"}],method:"POST"}),e.bi.prototype.get=c({Dh:{Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/<%=feature%>",Nh:{index:{type:"list"},yj:{type:"list",options:["_settings","_mappings","_warmers","_aliases"]}}},{Mh:"/<%=index%>",Nh:{index:{type:"list"}}}]}),e.bi.prototype.zj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}},{Mh:"/_alias"}]}),e.bi.prototype.Aj=c({Dh:{timeout:{type:"time"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_aliases/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_aliases",Nh:{index:{type:"list"}}},{Mh:"/_aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_aliases"}]}),e.bi.prototype.Bj=c({Dh:{Cj:{type:"boolean",name:"include_defaults"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>/field/<%=fields%>",Nh:{index:{type:"list"},type:{type:"list"},$h:{type:"list"}}},{Mh:"/<%=index%>/_mapping/field/<%=fields%>",Nh:{index:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/<%=type%>/field/<%=fields%>",Nh:{type:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/field/<%=fields%>",Nh:{$h:{type:"list"}}}]}),e.bi.prototype.Dj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_mapping",Nh:{index:{type:"list"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"list"}}},{Mh:"/_mapping"}]}),e.bi.prototype.oi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Sh:{type:"boolean"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_settings/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_settings"}]}),e.bi.prototype.aj=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_template/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_template"}]}),e.bi.prototype.Ej=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}]}),e.bi.prototype.Fj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_warmer",Nh:{index:{type:"list"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_warmer"}]}),e.bi.prototype.open=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"closed",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_open",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.Gj=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_optimize",Nh:{index:{type:"list"}}},{Mh:"/_optimize"}],method:"POST"}),e.bi.prototype.Lj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},method:"PUT"}),e.bi.prototype.Mj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},ol:{type:"boolean",name:"update_all_types"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"string"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.ui=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"}},Lh:[{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings"}],Oh:!0,method:"PUT"}),e.bi.prototype.Oj=c({Dh:{order:{type:"number"},create:{type:"boolean",default:!1},timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},Oh:!0,method:"PUT"}),e.bi.prototype.Pj=c({Dh:{Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_warmer/<%=name%>",Nh:{index:{type:"list"},type:{type:"list"},name:{type:"string"}}},{Mh:"/<%=index%>/_warmer/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},{Mh:"/_warmer/<%=name%>",Nh:{name:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.gi=c({Dh:{Qj:{type:"boolean",default:!1},Rj:{type:"boolean",default:!1,name:"active_only"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_recovery",Nh:{index:{type:"list"}}},{Mh:"/_recovery"}]}),e.bi.prototype.refresh=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},vj:{type:"boolean",default:!1},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_refresh",Nh:{index:{type:"list"}}},{Mh:"/_refresh"}],method:"POST"}),e.bi.prototype.hi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1},Jj:{name:"operation_threading"},ql:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_segments",Nh:{index:{type:"list"}}},{Mh:"/_segments"}]}),e.bi.prototype.rl=c({Dh:{status:{type:"list",options:["green","yellow","red","all"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_shard_stores",Nh:{index:{type:"list"}}},{Mh:"/_shard_stores"}]}),e.bi.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"list"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"indices",options:["cluster","indices","shards"]},types:{type:"list"}},Lh:[{Mh:"/<%=index%>/_stats/<%=metric%>",Nh:{index:{type:"list"},yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/<%=index%>/_stats",Nh:{index:{type:"list"}}},{Mh:"/_stats"}]}),e.bi.prototype.Wj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_aliases"},Oh:!0,method:"POST"}),e.bi.prototype.Xj=c({Dh:{Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},zi:{type:"boolean",name:"ignore_unavailable"},Yj:{type:"boolean",name:"wait_for_completion"},Zj:{type:"boolean",name:"only_ancient_segments"}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}],method:"POST"}),e.bi.prototype.$j=c({Dh:{xi:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},_j:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_validate/query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_validate/query",Nh:{index:{type:"list"}}},{Mh:"/_validate/query"}],method:"POST"}),e.info=c({url:{Mh:"/"}}),e.ak=c({Dh:{$h:{type:"list"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mget",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mget",Nh:{index:{type:"string"}}},{Mh:"/_mget"}],Oh:!0,method:"POST"}),e.uk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mpercolate",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mpercolate",Nh:{index:{type:"string"}}},{Mh:"/_mpercolate"}],Oh:!0,Ph:!0,method:"POST"}),e.vk=c({Dh:{rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_msearch",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_msearch",Nh:{index:{type:"list"}}},{Mh:"/_msearch"}],Oh:!0,Ph:!0,method:"POST"}),e.wk=c({Dh:{xk:{type:"list",required:!1},yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mtermvectors",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mtermvectors",Nh:{index:{type:"string"}}},{Mh:"/_mtermvectors"}],method:"POST"}),e.ei=d(),e.ei.prototype.Dk=c({Dh:{interval:{type:"time"},Ek:{type:"number"},Fk:{type:"number"},Gk:{type:"boolean",name:"ignore_idle_threads"},type:{type:"enum",options:["cpu","wait","block"]},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/hotthreads",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/hotthreads"}]}),e.ei.prototype.info=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/<%=metric%>",Nh:{yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins"]}}},{Mh:"/_nodes"}]}),e.ei.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"boolean"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"node",options:["node","indices","shards"]},types:{type:"list"},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats/<%=metric%>/<%=indexMetric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport"]}}},{Mh:"/_nodes/stats"}]}),e.Kk=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},Mk:{type:"string",name:"percolate_routing"},Nk:{type:"string",name:"percolate_preference"},Lk:{type:"enum",options:["ids"],name:"percolate_format"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.ping=c({url:{Mh:"/"},Ok:3e3,method:"HEAD"}),e.Pk=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},Oh:!0,method:"PUT"}),e.Oj=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},Oh:!0,method:"PUT"}),e.yl=c({Dh:{refresh:{type:"boolean"},timeout:{type:"time",default:"1m"},Ih:{type:"enum",options:["one","quorum","all"]},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_reindex"},Oh:!0,method:"POST"}),e.sl=c({Lh:[{Mh:"/_render/template/<%=id%>",Nh:{id:{type:"string"}}},{Mh:"/_render/template"}],method:"POST"}),e.scroll=c({Dh:{scroll:{type:"duration"},mi:{type:"string",name:"scroll_id"}},Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"string"}}},{Mh:"/_search/scroll"}],Qk:"scrollId",method:"POST"}),e.search=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","dfs_query_then_fetch","count","scan"],name:"search_type"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},tl:{type:"number",name:"terminate_after"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search",Nh:{index:{type:"list"}}},{Mh:"/_search"}],method:"POST"}),e.Wk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/exists",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/exists",Nh:{index:{type:"list"}}},{Mh:"/_search/exists"}],method:"POST"}),e.Xk=c({Dh:{Fi:{type:"string"},Kh:{type:"string"},Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search_shards",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search_shards",Nh:{index:{type:"list"}}},{Mh:"/_search_shards"}],method:"POST"}),e.Yk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch","count","scan"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/template",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/template",Nh:{index:{type:"list"}}},{Mh:"/_search/template"}],method:"POST"}),e.Vj=d(),e.Vj.prototype.create=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.$k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},verify:{type:"boolean"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"string"}}},Oh:!0,method:"POST"}),e.Vj.prototype.delete=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"DELETE"}),e.Vj.prototype._k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},method:"DELETE"}),e.Vj.prototype.get=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"list"}}}}),e.Vj.prototype.al=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},{Mh:"/_snapshot"}]}),e.Vj.prototype.restore=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_restore",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.status=c({Dh:{Th:{type:"time",name:"master_timeout"}},Lh:[{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_status",Nh:{Zk:{type:"string"},Vj:{type:"list"}}},{Mh:"/_snapshot/<%=repository%>/_status",Nh:{Zk:{type:"string"}}},{Mh:"/_snapshot/_status"}]}),e.Vj.prototype.bl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>/_verify",Nh:{Zk:{type:"string"}}},method:"POST"}),e.cl=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"string"}},Lh:[{Mh:"/<%=index%>/_suggest",Nh:{index:{type:"list"}}},{Mh:"/_suggest"}],Oh:!0,method:"POST"}),e.zl=d(),e.zl.prototype.cancel=c({Dh:{Yh:{type:"list",name:"node_id"},Al:{type:"list"},parentNode:{type:"string",name:"parent_node"},Bl:{type:"string",name:"parent_task"}},Lh:[{Mh:"/_tasks/<%=taskId%>/_cancel",Nh:{Cl:{type:"number"}}},{Mh:"/_tasks/_cancel"}],method:"POST"}),e.zl.prototype.list=c({Dh:{Yh:{type:"list",name:"node_id"},Al:{type:"list"},Qj:{type:"boolean"},parentNode:{type:"string",name:"parent_node"},Bl:{type:"string",name:"parent_task"},Yj:{type:"boolean",name:"wait_for_completion"}},Lh:[{Mh:"/_tasks/<%=taskId%>",Nh:{Cl:{type:"string"}}},{Mh:"/_tasks"}]}),e.ul=c({Dh:{yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},vl:{type:"boolean",default:!1,required:!1},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.update=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},$h:{type:"list"},lang:{type:"string"},parent:{type:"string"},refresh:{type:"boolean"},el:{type:"number",name:"retry_on_conflict"},Kh:{type:"string"},fl:{},gl:{name:"script_id"},hl:{type:"boolean",name:"scripted_upsert"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_update",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Dl=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},El:{type:"enum",default:"abort",options:["abort","proceed"]},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","dfs_query_then_fetch"],name:"search_type"},Fl:{type:"time",name:"search_timeout"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},tl:{type:"number",name:"terminate_after"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time",default:"1m"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},Qi:{type:"boolean",name:"version_type"},pl:{type:"boolean",name:"request_cache"},refresh:{type:"boolean"},Ih:{type:"enum",options:["one","quorum","all"]},Gl:{type:"integer",name:"scroll_size"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_update_by_query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_update_by_query",Nh:{index:{type:"list"}}}],method:"POST"}),e.create=c.il(e.index,{transform:function(a){a.jl="create"}})},{kl:29,ll:50}],25:[function(a,b){b.g=a(24)},{kl:29,ll:50}],26:[function(a,b){b.g={Hl:a("./2_3"),2.3:a("./2_3"),2.2:a("./2_2"),2.1:a("./2_1"),"2.0":a("./2_0"),1.7:a("./1_7"),Il:a("./2_x"),di:a("./master")}},{Jl:20,Kl:21,Ll:22,Ml:23,Nl:24,Ol:25,Pl:27}],27:[function(a,b){var c=a("../client_action").Ch(function(b){return a("../utils").Hd(b,{Dh:{Eh:{type:"list",name:"filter_path"}}})}),d=a("../client_action").Fh,e=b.g={};e.Gh=["cat","cluster","indices","ingest","nodes","reindex","snapshot","tasks"],e.Hh=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},type:{type:"string"},$h:{type:"list"},Ql:{type:"string"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_bulk",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_bulk",Nh:{index:{type:"string"}}},{Mh:"/_bulk"}],Oh:!0,Ph:!0,method:"POST"}),e.Qh=d(),e.Qh.prototype.Rh=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/aliases/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_cat/aliases"}]}),e.Qh.prototype.Wh=c({Dh:{format:{type:"string"},Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/allocation/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cat/allocation"}]}),e.Qh.prototype.count=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/count/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/count"}]}),e.Qh.prototype.Zh=c({Dh:{format:{type:"string"},Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},$h:{type:"list"}},Lh:[{Mh:"/_cat/fielddata/<%=fields%>",Nh:{$h:{type:"list"}}},{Mh:"/_cat/fielddata"}]}),e.Qh.prototype._h=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"
},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ai:{type:"boolean",default:!0},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/health"}}),e.Qh.prototype.Vh=c({Dh:{Vh:{type:"boolean",default:!1}},url:{Mh:"/_cat"}}),e.Qh.prototype.bi=c({Dh:{format:{type:"string"},Xh:{type:"enum",options:["b","k","m","g"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},ci:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/indices/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/indices"}]}),e.Qh.prototype.di=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/master"}}),e.Qh.prototype.ml=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodeattrs"}}),e.Qh.prototype.ei=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/nodes"}}),e.Qh.prototype.fi=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/pending_tasks"}}),e.Qh.prototype.plugins=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/plugins"}}),e.Qh.prototype.gi=c({Dh:{format:{type:"string"},Xh:{type:"enum",options:["b","k","m","g"]},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/recovery/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/recovery"}]}),e.Qh.prototype.wl=c({Dh:{format:{type:"string"},Sh:{type:"boolean",default:!1},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/repositories"}}),e.Qh.prototype.hi=c({Dh:{format:{type:"string"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/segments/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/segments"}]}),e.Qh.prototype.ii=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},Lh:[{Mh:"/_cat/shards/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cat/shards"}]}),e.Qh.prototype.Ek=c({Dh:{format:{type:"string"},zi:{type:"boolean",default:!1,name:"ignore_unavailable"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1}},url:{Mh:"/_cat/snapshots/<%=repository%>",Nh:{Zk:{type:"list"}}}}),e.Qh.prototype.ji=c({Dh:{format:{type:"string"},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},Uh:{type:"list"},Vh:{type:"boolean",default:!1},Yg:{type:"boolean",default:!1},ki:{type:"boolean",default:!1,name:"full_id"}},url:{Mh:"/_cat/thread_pool"}}),e.li=c({Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"list"}}},{Mh:"/_search/scroll"}],method:"DELETE"}),e.ni=d(),e.ni.prototype.Rl=c({Dh:{Sl:{type:"boolean",name:"include_yes_decisions"}},url:{Mh:"/_cluster/allocation/explain"},method:"POST"}),e.ni.prototype.oi=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},Cj:{type:"boolean",default:!1,name:"include_defaults"}},url:{Mh:"/_cluster/settings"}}),e.ni.prototype._h=c({Dh:{level:{type:"enum",default:"cluster",options:["cluster","indices","shards"]},Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},qi:{type:"number",name:"wait_for_active_shards"},ri:{type:"string",name:"wait_for_nodes"},si:{type:"number",name:"wait_for_relocating_shards"},ti:{type:"enum",default:null,options:["green","yellow","red"],name:"wait_for_status"}},Lh:[{Mh:"/_cluster/health/<%=index%>",Nh:{index:{type:"list"}}},{Mh:"/_cluster/health"}]}),e.ni.prototype.fi=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_cluster/pending_tasks"}}),e.ni.prototype.ui=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/settings"},method:"PUT"}),e.ni.prototype.vi=c({Dh:{wi:{type:"boolean",name:"dry_run"},xi:{type:"boolean"},yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","master_node","version"]},Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_cluster/reroute"},method:"POST"}),e.ni.prototype.state=c({Dh:{Sh:{type:"boolean"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/_cluster/state/<%=metric%>/<%=index%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]},index:{type:"list"}}},{Mh:"/_cluster/state/<%=metric%>",Nh:{yi:{type:"list",options:["_all","blocks","metadata","nodes","routing_table","routing_nodes","master_node","version"]}}},{Mh:"/_cluster/state"}]}),e.ni.prototype.Ci=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_cluster/stats/nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_cluster/stats"}]}),e.count=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Ei:{type:"number",name:"min_score"},Fi:{type:"string"},Kh:{type:"string"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_count",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_count",Nh:{index:{type:"list"}}},{Mh:"/_count"}],method:"POST"}),e.Ni=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate/count",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.delete=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Si=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},method:"DELETE"}),e.Ti=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},method:"DELETE"}),e.Ui=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"HEAD"}),e.xi=c({Dh:{Ii:{type:"boolean",name:"analyze_wildcard"},Hi:{type:"string"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},$h:{type:"list"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},parent:{type:"string"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_explain",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Zi=c({Dh:{$h:{type:"list"},level:{type:"enum",default:"cluster",options:["indices","cluster"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_field_stats",Nh:{index:{type:"list"}}},{Mh:"/_field_stats"}],method:"POST"}),e.get=c({Dh:{$h:{type:"list"},parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.$i=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}}}),e._i=c({Dh:{parent:{type:"string"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Kh:{type:"string"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_source",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}}}),e.aj=c({Dh:{version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}}}),e.index=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},parent:{type:"string"},refresh:{type:"boolean"},Kh:{type:"string"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"},Ql:{type:"string"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"string"},type:{type:"string"}}}],Oh:!0,method:"POST"}),e.bi=d(),e.bi.prototype.dj=c({Dh:{Hi:{type:"string"},ej:{type:"list",name:"char_filters"},fj:{type:"string"},filters:{type:"list"},index:{type:"string"},gj:{type:"boolean",name:"prefer_local"},text:{type:"list"},hj:{type:"string"},xi:{type:"boolean"},attributes:{type:"list"},format:{type:"enum",default:"detailed",options:["detailed","text"]}},Lh:[{Mh:"/<%=index%>/_analyze",Nh:{index:{type:"string"}}},{Mh:"/_analyze"}],method:"POST"}),e.bi.prototype.ij=c({Dh:{jj:{type:"boolean",name:"field_data"},Zh:{type:"boolean"},$h:{type:"list"},ua:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},index:{type:"list"},nj:{type:"boolean"},nl:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_cache/clear",Nh:{index:{type:"list"}}},{Mh:"/_cache/clear"}],method:"POST"}),e.bi.prototype.close=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_close",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.create=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},ol:{type:"boolean",name:"update_all_types"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"string"}}},method:"POST"}),e.bi.prototype.delete=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"DELETE"}),e.bi.prototype.pj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},method:"DELETE"}),e.bi.prototype.Ti=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"DELETE"}),e.bi.prototype.Ui=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>",Nh:{index:{type:"list"}}},method:"HEAD"}),e.bi.prototype.sj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}}],method:"HEAD"}),e.bi.prototype.tj=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},method:"HEAD"}),e.bi.prototype.uj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},url:{Mh:"/<%=index%>/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},method:"HEAD"}),e.bi.prototype.flush=c({Dh:{vj:{type:"boolean"},wj:{type:"boolean",name:"wait_if_ongoing"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush",Nh:{index:{type:"list"}}},{Mh:"/_flush"}],method:"POST"}),e.bi.prototype.xj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/_flush/synced",Nh:{index:{type:"list"}}},{Mh:"/_flush/synced"}],method:"POST"}),e.bi.prototype.xl=c({Dh:{flush:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Hj:{type:"number",name:"max_num_segments"},Ij:{type:"boolean",name:"only_expunge_deletes"},Jj:{name:"operation_threading"},Kj:{type:"boolean",name:"wait_for_merge"}},Lh:[{Mh:"/<%=index%>/_forcemerge",Nh:{index:{type:"list"}}},{Mh:"/_forcemerge"}],method:"POST"}),e.bi.prototype.get=c({Dh:{Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},Cj:{type:"boolean",default:!1,name:"include_defaults"}},Lh:[{Mh:"/<%=index%>/<%=feature%>",Nh:{index:{type:"list"},yj:{type:"list",options:["_settings","_mappings","_aliases"]}}},{Mh:"/<%=index%>",Nh:{index:{type:"list"}}}]}),e.bi.prototype.zj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"all",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/_alias/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/<%=index%>/_alias",Nh:{index:{type:"list"}}},{Mh:"/_alias"}]}),e.bi.prototype.Bj=c({Dh:{Cj:{type:"boolean",name:"include_defaults"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>/field/<%=fields%>",Nh:{index:{type:"list"},type:{type:"list"},$h:{type:"list"}}},{Mh:"/<%=index%>/_mapping/field/<%=fields%>",Nh:{index:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/<%=type%>/field/<%=fields%>",Nh:{type:{type:"list"},$h:{type:"list"}}},{Mh:"/_mapping/field/<%=fields%>",Nh:{$h:{type:"list"}}}]}),e.bi.prototype.Dj=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Sh:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_mapping",Nh:{index:{type:"list"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"list"}}},{Mh:"/_mapping"}]}),e.bi.prototype.oi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:["open","closed"],options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"},Sh:{type:"boolean"},Di:{type:"boolean",default:!1},Cj:{type:"boolean",default:!1,name:"include_defaults"}},Lh:[{Mh:"/<%=index%>/_settings/<%=name%>",Nh:{index:{type:"list"},name:{type:"list"}}},{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_settings"}]}),e.bi.prototype.aj=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_template/<%=name%>",Nh:{name:{type:"list"}}},{Mh:"/_template"}]}),e.bi.prototype.Ej=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}]}),e.bi.prototype.open=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"closed",options:["open","closed","none","all"],name:"expand_wildcards"}},url:{Mh:"/<%=index%>/_open",Nh:{index:{type:"list"}}},method:"POST"}),e.bi.prototype.Lj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/<%=index%>/_alias/<%=name%>",Nh:{index:{type:"list"},name:{type:"string"}}},method:"PUT"}),e.bi.prototype.Mj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},ol:{type:"boolean",name:"update_all_types"}},Lh:[{Mh:"/<%=index%>/_mapping/<%=type%>",Nh:{index:{type:"list"},type:{type:"string"}}},{Mh:"/_mapping/<%=type%>",Nh:{type:{type:"string"}}}],Oh:!0,method:"PUT"}),e.bi.prototype.ui=c({Dh:{Th:{type:"time",name:"master_timeout"},Tl:{type:"boolean",name:"preserve_existing"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},pi:{type:"boolean",name:"flat_settings"}},Lh:[{Mh:"/<%=index%>/_settings",Nh:{index:{type:"list"}}},{Mh:"/_settings"}],Oh:!0,method:"PUT"}),e.bi.prototype.Oj=c({Dh:{order:{type:"number"},create:{type:"boolean",default:!1},timeout:{type:"time"},Th:{type:"time",name:"master_timeout"},pi:{type:"boolean",name:"flat_settings"}},url:{Mh:"/_template/<%=name%>",Nh:{name:{type:"string"}}},Oh:!0,method:"PUT"}),e.bi.prototype.gi=c({Dh:{Qj:{type:"boolean",default:!1},Rj:{type:"boolean",default:!1,name:"active_only"},Di:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_recovery",Nh:{index:{type:"list"}}},{Mh:"/_recovery"}]}),e.bi.prototype.refresh=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},vj:{type:"boolean",default:!1},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_refresh",Nh:{index:{type:"list"}}},{Mh:"/_refresh"}],method:"POST"}),e.bi.prototype.hi=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Di:{type:"boolean",default:!1},Jj:{name:"operation_threading"},ql:{type:"boolean",default:!1}},Lh:[{Mh:"/<%=index%>/_segments",Nh:{index:{type:"list"}}},{Mh:"/_segments"}]}),e.bi.prototype.rl=c({Dh:{status:{type:"list",options:["green","yellow","red","all"]},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"}},Lh:[{Mh:"/<%=index%>/_shard_stores",Nh:{index:{type:"list"}}},{Mh:"/_shard_stores"}]}),e.bi.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"list"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"indices",options:["cluster","indices","shards"]},types:{type:"list"}},Lh:[{Mh:"/<%=index%>/_stats/<%=metric%>",Nh:{index:{type:"list"},yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/<%=index%>/_stats",Nh:{index:{type:"list"}}},{Mh:"/_stats"}]}),e.bi.prototype.Wj=c({Dh:{timeout:{type:"time"},Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_aliases"},Oh:!0,method:"POST"}),e.bi.prototype.Xj=c({Dh:{Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},zi:{type:"boolean",name:"ignore_unavailable"},Yj:{type:"boolean",name:"wait_for_completion"},Zj:{type:"boolean",name:"only_ancient_segments"}},Lh:[{Mh:"/<%=index%>/_upgrade",Nh:{index:{type:"list"}}},{Mh:"/_upgrade"}],method:"POST"}),e.bi.prototype.$j=c({Dh:{xi:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Jj:{name:"operation_threading"},Gi:{type:"string"},Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},_j:{type:"boolean"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_validate/query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_validate/query",Nh:{index:{type:"list"}}},{Mh:"/_validate/query"}],method:"POST"}),e.info=c({url:{Mh:"/"}}),e.Ul=d(),e.Ul.prototype.Vl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_ingest/pipeline/<%=id%>",Nh:{id:{type:"string"}}},method:"DELETE"}),e.Ul.prototype.Wl=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_ingest/pipeline/<%=id%>",Nh:{id:{type:"string"}}}}),e.Ul.prototype.Xl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_ingest/pipeline/<%=id%>",Nh:{id:{type:"string"}}},Oh:!0,method:"PUT"}),e.Ul.prototype.Yl=c({Dh:{ql:{type:"boolean",default:!1}},Lh:[{Mh:"/_ingest/pipeline/<%=id%>/_simulate/",Nh:{id:{type:"string"}}},{Mh:"/_ingest/pipeline/_simulate"}],Oh:!0,method:"POST"}),e.ak=c({Dh:{$h:{type:"list"},Fi:{type:"string"},Vi:{type:"boolean"},refresh:{type:"boolean"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mget",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mget",Nh:{index:{type:"string"}}},{Mh:"/_mget"}],Oh:!0,method:"POST"}),e.uk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mpercolate",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mpercolate",Nh:{index:{type:"string"}}},{Mh:"/_mpercolate"}],Oh:!0,Ph:!0,method:"POST"}),e.vk=c({Dh:{rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_msearch",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_msearch",Nh:{index:{type:"list"}}},{Mh:"/_msearch"}],Oh:!0,Ph:!0,method:"POST"}),e.wk=c({Dh:{xk:{type:"list",required:!1},yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_mtermvectors",Nh:{index:{type:"string"},type:{type:"string"}}},{Mh:"/<%=index%>/_mtermvectors",Nh:{index:{type:"string"}}},{Mh:"/_mtermvectors"}],method:"POST"}),e.ei=d(),e.ei.prototype.Dk=c({Dh:{interval:{type:"time"},Ek:{type:"number"},Fk:{type:"number"},Gk:{type:"boolean",name:"ignore_idle_threads"},type:{type:"enum",options:["cpu","wait","block"]},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/hotthreads",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/hotthreads"}]}),e.ei.prototype.info=c({Dh:{pi:{type:"boolean",name:"flat_settings"},Di:{type:"boolean",default:!1},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins","ingest"]}}},{Mh:"/_nodes/<%=nodeId%>",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/<%=metric%>",Nh:{yi:{type:"list",options:["settings","os","process","jvm","thread_pool","transport","http","plugins","ingest"]}}},{Mh:"/_nodes"}]}),e.ei.prototype.Ci=c({Dh:{Sj:{type:"list",name:"completion_fields"},Tj:{type:"list",name:"fielddata_fields"},$h:{type:"list"},Uj:{type:"boolean"},Di:{type:"boolean",default:!1},level:{type:"enum",default:"node",options:["node","indices","shards"]},types:{type:"list"},timeout:{type:"time"}},Lh:[{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>/<%=indexMetric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport","discovery"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats/<%=metric%>",Nh:{Yh:{type:"list"},yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport","discovery"]}}},{Mh:"/_nodes/stats/<%=metric%>/<%=indexMetric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport","discovery"]},Jk:{type:"list",options:["_all","completion","docs","fielddata","query_cache","flush","get","indexing","merge","percolate","request_cache","refresh","search","segments","store","warmer","suggest"]}}},{Mh:"/_nodes/<%=nodeId%>/stats",Nh:{Yh:{type:"list"}}},{Mh:"/_nodes/stats/<%=metric%>",Nh:{yi:{type:"list",options:["_all","breaker","fs","http","indices","jvm","os","process","thread_pool","transport","discovery"]}}},{Mh:"/_nodes/stats"}]}),e.Kk=c({Dh:{Kh:{type:"list"},Fi:{type:"string"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Oi:{type:"string",name:"percolate_index"},Pi:{type:"string",name:"percolate_type"},Mk:{type:"string",name:"percolate_routing"},Nk:{type:"string",name:"percolate_preference"},Lk:{type:"enum",options:["ids"],name:"percolate_format"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_percolate",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.ping=c({url:{Mh:"/"},Ok:3e3,method:"HEAD"}),e.Pk=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_scripts/<%=lang%>/<%=id%>",Nh:{lang:{type:"string"},id:{type:"string"}}},Oh:!0,method:"PUT"}),e.Oj=c({Dh:{bj:{type:"enum",default:"index",options:["index","create"],name:"op_type"},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},url:{Mh:"/_search/template/<%=id%>",Nh:{id:{type:"string"}}},Oh:!0,method:"PUT"}),e.yl=d(),e.yl=c({Dh:{refresh:{type:"boolean"},timeout:{type:"time",default:"1m"},Ih:{type:"enum",options:["one","quorum","all"]},Yj:{type:"boolean",default:!1,name:"wait_for_completion"},Zl:{type:"float",default:0,name:"requests_per_second"}},url:{Mh:"/_reindex"},Oh:!0,method:"POST"}),e.yl.prototype.$l=c({Dh:{Zl:{type:"float",default:0,name:"requests_per_second"}},url:{Mh:"/_reindex/<%=taskId%>/_rethrottle",Nh:{Cl:{type:"string"}}},method:"POST"}),e.sl=c({Lh:[{Mh:"/_render/template/<%=id%>",Nh:{id:{type:"string"}}},{Mh:"/_render/template"}],method:"POST"}),e.scroll=c({Dh:{scroll:{type:"duration"},mi:{type:"string",name:"scroll_id"}},Lh:[{Mh:"/_search/scroll/<%=scrollId%>",Nh:{mi:{type:"string"}}},{Mh:"/_search/scroll"}],Qk:"scrollId",method:"POST"}),e.search=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","dfs_query_then_fetch"],name:"search_type"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},tl:{type:"number",name:"terminate_after"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},pl:{type:"boolean",name:"request_cache"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search",Nh:{index:{
type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search",Nh:{index:{type:"list"}}},{Mh:"/_search"}],method:"POST"}),e.Xk=c({Dh:{Fi:{type:"string"},Kh:{type:"string"},Sh:{type:"boolean"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search_shards",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search_shards",Nh:{index:{type:"list"}}},{Mh:"/_search_shards"}],method:"POST"}),e.Yk=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","query_and_fetch","dfs_query_then_fetch","dfs_query_and_fetch"],name:"search_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_search/template",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_search/template",Nh:{index:{type:"list"}}},{Mh:"/_search/template"}],method:"POST"}),e.Vj=d(),e.Vj.prototype.create=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.$k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"},verify:{type:"boolean"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"string"}}},Oh:!0,method:"POST"}),e.Vj.prototype.delete=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"DELETE"}),e.Vj.prototype._k=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},method:"DELETE"}),e.Vj.prototype.get=c({Dh:{Th:{type:"time",name:"master_timeout"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>",Nh:{Zk:{type:"string"},Vj:{type:"list"}}}}),e.Vj.prototype.al=c({Dh:{Th:{type:"time",name:"master_timeout"},Sh:{type:"boolean"}},Lh:[{Mh:"/_snapshot/<%=repository%>",Nh:{Zk:{type:"list"}}},{Mh:"/_snapshot"}]}),e.Vj.prototype.restore=c({Dh:{Th:{type:"time",name:"master_timeout"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"}},url:{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_restore",Nh:{Zk:{type:"string"},Vj:{type:"string"}}},method:"POST"}),e.Vj.prototype.status=c({Dh:{Th:{type:"time",name:"master_timeout"}},Lh:[{Mh:"/_snapshot/<%=repository%>/<%=snapshot%>/_status",Nh:{Zk:{type:"string"},Vj:{type:"list"}}},{Mh:"/_snapshot/<%=repository%>/_status",Nh:{Zk:{type:"string"}}},{Mh:"/_snapshot/_status"}]}),e.Vj.prototype.bl=c({Dh:{Th:{type:"time",name:"master_timeout"},timeout:{type:"time"}},url:{Mh:"/_snapshot/<%=repository%>/_verify",Nh:{Zk:{type:"string"}}},method:"POST"}),e.cl=c({Dh:{zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Fi:{type:"string"},Kh:{type:"string"}},Lh:[{Mh:"/<%=index%>/_suggest",Nh:{index:{type:"list"}}},{Mh:"/_suggest"}],Oh:!0,method:"POST"}),e.zl=d(),e.zl.prototype.cancel=c({Dh:{Yh:{type:"list",name:"node_id"},Al:{type:"list"},parentNode:{type:"string",name:"parent_node"},Bl:{type:"string",name:"parent_task"}},Lh:[{Mh:"/_tasks/<%=taskId%>/_cancel",Nh:{Cl:{type:"string"}}},{Mh:"/_tasks/_cancel"}],method:"POST"}),e.zl.prototype.list=c({Dh:{Yh:{type:"list",name:"node_id"},Al:{type:"list"},Qj:{type:"boolean"},parentNode:{type:"string",name:"parent_node"},Bl:{type:"string",name:"parent_task"},Yj:{type:"boolean",name:"wait_for_completion"},wd:{type:"enum",default:"nodes",options:["nodes","parents"],name:"group_by"}},Lh:[{Mh:"/_tasks/<%=taskId%>",Nh:{Cl:{type:"string"}}},{Mh:"/_tasks"}]}),e.ul=c({Dh:{yk:{type:"boolean",default:!1,required:!1,name:"term_statistics"},zk:{type:"boolean",default:!0,required:!1,name:"field_statistics"},$h:{type:"list",required:!1},Ak:{type:"boolean",default:!0,required:!1},Bk:{type:"boolean",default:!0,required:!1},Ck:{type:"boolean",default:!0,required:!1},Fi:{type:"string",required:!1},Kh:{type:"string",required:!1},parent:{type:"string",required:!1},Vi:{type:"boolean",required:!1},version:{type:"number"},Qi:{type:"enum",options:["internal","external","external_gte","force"],name:"version_type"}},Lh:[{Mh:"/<%=index%>/<%=type%>/<%=id%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},{Mh:"/<%=index%>/<%=type%>/_termvectors",Nh:{index:{type:"string"},type:{type:"string"}}}],method:"POST"}),e.update=c({Dh:{Ih:{type:"enum",options:["one","quorum","all"]},$h:{type:"list"},lang:{type:"string"},parent:{type:"string"},refresh:{type:"boolean"},el:{type:"number",name:"retry_on_conflict"},Kh:{type:"string"},fl:{},gl:{name:"script_id"},hl:{type:"boolean",name:"scripted_upsert"},timeout:{type:"time"},timestamp:{type:"time"},cj:{type:"duration"},version:{type:"number"},Qi:{type:"enum",options:["internal","force"],name:"version_type"}},url:{Mh:"/<%=index%>/<%=type%>/<%=id%>/_update",Nh:{index:{type:"string"},type:{type:"string"},id:{type:"string"}}},method:"POST"}),e.Dl=c({Dh:{Hi:{type:"string"},Ii:{type:"boolean",name:"analyze_wildcard"},Ji:{type:"enum",default:"OR",options:["AND","OR"],name:"default_operator"},Ki:{type:"string"},xi:{type:"boolean"},$h:{type:"list"},Tj:{type:"list",name:"fielddata_fields"},from:{type:"number"},zi:{type:"boolean",name:"ignore_unavailable"},Ai:{type:"boolean",name:"allow_no_indices"},El:{type:"enum",default:"abort",options:["abort","proceed"]},Bi:{type:"enum",default:"open",options:["open","closed","none","all"],name:"expand_wildcards"},Li:{type:"boolean"},Mi:{type:"boolean",name:"lowercase_expanded_terms"},Ql:{type:"string"},Fi:{type:"string"},Gi:{type:"string"},Kh:{type:"list"},scroll:{type:"duration"},rk:{type:"enum",options:["query_then_fetch","dfs_query_then_fetch"],name:"search_type"},Fl:{type:"time",name:"search_timeout"},size:{type:"number"},sort:{type:"list"},Wi:{type:"list"},Xi:{type:"list",name:"_source_exclude"},Yi:{type:"list",name:"_source_include"},tl:{type:"number",name:"terminate_after"},Ci:{type:"list"},Rk:{type:"string",name:"suggest_field"},Sk:{type:"enum",default:"missing",options:["missing","popular","always"],name:"suggest_mode"},Tk:{type:"number",name:"suggest_size"},Uk:{type:"text",name:"suggest_text"},timeout:{type:"time",default:"1m"},Vk:{type:"boolean",name:"track_scores"},version:{type:"boolean"},Qi:{type:"boolean",name:"version_type"},pl:{type:"boolean",name:"request_cache"},refresh:{type:"boolean"},Ih:{type:"enum",options:["one","quorum","all"]},Gl:{type:"integer",name:"scroll_size"},Yj:{type:"boolean",default:!1,name:"wait_for_completion"},Zl:{type:"float",default:0,name:"requests_per_second"}},Lh:[{Mh:"/<%=index%>/<%=type%>/_update_by_query",Nh:{index:{type:"list"},type:{type:"list"}}},{Mh:"/<%=index%>/_update_by_query",Nh:{index:{type:"list"}}}],method:"POST"}),e.create=c.il(e.index,{transform:function(a){a.jl="create"}})},{kl:29,ll:50}],28:[function(a,b){function c(b){function g(){b.hasOwnProperty("log")||(b.log="warning"),b._l||b.host||(b.host="http://localhost:9200"),this.close=function(){this.am.close()},this.am=new d(b),f.xe(g.prototype,function(a,b){a.prototype instanceof e.bm&&(this[b]=new a(this.am))},this),delete this.Gh}if(b=b||{},b.cm)throw Error("Do not reuse objects to configure the elasticsearch Client class: https://github.com/elasticsearch/elasticsearch-js/issues/33");b.cm=!0,g.prototype=f.dm(b,"apiVersion",c.em,"_default"),b.fm||g.prototype!==c.em["0.90"]||(b.fm="/_cluster/nodes");var h=g;return b.plugins&&(h.prototype=f.Ee(h.prototype),f.xe(b.plugins,function(c){h=c(h,b,{em:a("./apis"),gm:a("./connectors"),hm:a("./loggers"),im:a("./selectors"),jm:a("./serializers"),uh:a("./client"),km:e,lm:a("./connection"),vh:a("./connection_pool"),mm:a("./errors"),nm:a("./host"),om:a("./log"),pm:a("./logger"),qm:a("./nodes_to_host"),wh:a("./transport"),rm:a("./utils")})||h})),new h}b.g=c;var d=a("./transport"),e=a("./client_action"),f=a("./utils");c.em=a("./apis")},{sm:26,tm:28,um:29,vm:30,wm:31,xm:32,ym:34,zm:35,Am:36,Bm:37,Cm:38,Dm:40,Em:41,Fm:45,Gm:47,Hm:50}],29:[function(a,b,c){function d(a){a=a||h.identity;var b=function(b){function c(a,c){"function"==typeof a?(c=a,a={}):(a=a||{},c="function"==typeof c?c:null);try{return f(this.am,b,h.clone(a),c)}catch(a){if("function"!=typeof c){var d=this.am.defer();return d.reject(a),d.ph}h.i(c,a)}}return b=a(b),h.Ue(b.Dh)||(b.Dh={}),b.method||(b.method="GET"),c.Im=b,c};return b.il=function(a,b){return function(c,d){return"function"==typeof c?(d=c,c={}):(c=c||{},d="function"==typeof d?d:null),b.transform&&b.transform(c),a.call(this,c,d)}},b}function e(a,b){var c,d,e={};if(a.Nh)for(a.Jm||(a.Jm=h.keys(a.Nh)),c=0;c<a.Jm.length;c++){if(d=a.Jm[c],!b.hasOwnProperty(d)||null==b[d])return!1;i[a.Nh[d].type]?e[d]=i[a.Nh[d].type](a.Nh[d],b[d],d):e[d]=b[d]}if(a.opt)for(a.Km||(a.Km=h.keys(a.opt)),c=0;c<a.Km.length;c++)d=a.Km[c],b[d]?i[a.opt[d].type]||null==b[d]?e[d]=i[a.opt[d].type](a.opt[d],b[d],d):e[d]=b[d]:e[d]=a.opt[d].default;return a.if||(a.if=h.if(a.Mh)),a.if(h.transform(e,function(a,c,d){a[d]=encodeURIComponent(c),delete b[d]},{}))}function f(a,b,c,d){var f,g={method:b.method},j={};if(b.Ok&&(g.Ok=b.Ok),!c.body&&b.Qk&&(c.body=c[b.Qk],delete c[b.Qk]),b.needsBody&&!c.body)throw new TypeError("A request body is required.");if(b.Ph&&(g.Ph=!0),"HEAD"===b.method&&(g.Lm=!0),b.url)g.path=e(b.url,c);else for(f=0;f<b.Lh.length&&!(g.path=e(b.Lh[f],c));f++);if(!g.path){var k=b.url||b.Lh[b.Lh.length-1];throw new TypeError("Unable to build a path with those params. Supply at least "+h.keys(k.Nh).join(", "))}b.Mm||(b.Mm=h.keys(b.Dh),b.Nm=h.transform(b.Dh,function(a,b,c){b.required&&a.push(c)},[]));for(var l in c)if(c.hasOwnProperty(l)&&null!=c[l])switch(l){case"body":case"headers":case"requestTimeout":case"maxRetries":g[l]=c[l];break;case"ignore":g.Om=h.isArray(c[l])?c[l]:[c[l]];break;case"method":g.method=h.Pm(c[l]);break;default:var m=b.Dh[l];m?(m.name=m.name||l,null!=c[l]&&(i[m.type]?j[m.name]=i[m.type](m,c[l],l):j[m.name]=c[l],m.default&&j[m.name]===m.default&&delete j[m.name])):j[l]=c[l]}for(f=0;f<b.Nm.length;f++)if(!j.hasOwnProperty(b.Nm[f]))throw new TypeError("Missing required parameter "+b.Nm[f]);return g.ua=j,a.nl(g,d)}function g(a){return a.split(",").map(function(a){return a.trim()})}var h=a("./utils");c.Ch=d,c.Qm=d(),c.Rm=c.Qm.il,c.Sm=e,c.bm=function(){},c.Fh=function(){function a(a){this.am=a}return a.prototype=new c.bm,a};var i={Tm:function a(b,c,d){if(h.u(c)&&c.indexOf(",")>-1&&(c=g(c)),h.isArray(c))return c.map(function(c){return a(b,c,d)}).join(",");for(var e=0;e<b.options.length;e++)if(b.options[e]==c)return b.options[e];throw new TypeError("Invalid "+d+": expected "+(b.options.length>1?"one of "+b.options.join(","):b.options[0]))},duration:function(a,b,c){if(h.Um(b)||h.Vm(b))return b;throw new TypeError("Invalid "+c+": expected a number or interval (an integer followed by one of M, w, d, h, m, s, y or ms).")},list:function(a,b,c){switch(typeof b){case"number":case"boolean":return""+b;case"string":b=g(b);case"object":if(h.isArray(b))return b.join(",");default:throw new TypeError("Invalid "+c+": expected be a comma separated list, array, number or string.")}},eb:function(a,b){return b=h.u(b)?b.toLowerCase():b,"no"===b||"off"===b?!1:!!b},number:function(a,b,c){if(h.Um(b))return 1*b;throw new TypeError("Invalid "+c+": expected a number.")},gb:function(a,b,c){switch(typeof b){case"number":case"string":return""+b;default:throw new TypeError("Invalid "+c+": expected a string.")}},time:function(a,b,c){if("string"==typeof b)return b;if(h.Um(b))return""+b;if(b instanceof Date)return""+b.getTime();throw new TypeError("Invalid "+c+": expected some sort of time.")}}},{Hm:50}],30:[function(a,b){function c(a,b){if(b=b||{},e.call(this),this.log=b.log||new f,this.Wm=b.Wm||3e3,!a)throw new TypeError("Missing host");if(!(a instanceof g))throw new TypeError("Invalid host");this.host=a,d.Xm(this)}b.g=c;var d=a("./utils"),e=a("events").X,f=a("./log"),g=a("./host"),h=a("./errors");d.H(c,e),c.prototype.nl=function(){throw Error("Connection#request must be overwritten by the Connector")},c.prototype.ping=function(a,b){"function"==typeof a?(b=a,a=null):b="function"==typeof b?b:null;var c,e,f,g=this.Wm;a&&a.hasOwnProperty("requestTimeout")&&(g=a.Ok),f=this.nl(d.Qc(a||{},{path:"/",method:"HEAD"}),function(a){e||(clearTimeout(c),b&&b(a))}),g&&(c=setTimeout(function(){f&&f(),e=!0,b&&b(new h.Ym("Ping Timeout after "+g+"ms"))},g))},c.prototype.Zm=function(a){var b=this.status;this.status=a,this.$("status set",a,b,this),"closed"===a&&this.ca()}},{ym:34,zm:35,Am:36,Hm:50,$m:6}],31:[function(a,b){function c(a){a=a||{},e.Xm(this),a.log?this.log=a.log:(this.log=new f,a.log=this.log),this._m=a,this.selector=e.dm(a,"selector",c.im,c.an),this.lm=e.dm(a,"connectionClass",c.bn,c.cn),this.dn=a.hasOwnProperty("deadTimeout")?a.dn:6e4,this.en=a.hasOwnProperty("maxDeadTimeout")?a.en:18e5,this.fn=e.dm(a,"calcDeadTimeout",c.gn,"exponential"),this.index={},this.hn={in:[],jn:[]},this.kn=[]}var d=a("__browserify_process");b.g=c;var e=a("./utils"),f=a("./log");c.im=a("./selectors"),c.an="roundRobin",c.bn=a("./connectors"),c.cn=c.bn.Hl,delete c.bn.Hl,c.gn={ln:function(a,b){return b},mn:function(a,b){return Math.min(2*b*Math.pow(2,.5*a-1),this.en)}},c.prototype.select=function(a){if(this.hn.in.length)if(this.selector.length>1)this.selector(this.hn.in,a);else try{e.i(a,void 0,this.selector(this.hn.in))}catch(b){a(b)}else this.kn.length?this.nn(a):e.i(a,void 0)},c.prototype.on=e.pn(function(a,b,c){var d,f="dead"===a,g=f&&"dead"===b,h=!f&&"dead"===b,i=b===a,j=this.hn[b],k=this.hn[a];return i&&!f?!0:(j!==k&&(e.isArray(j)&&(d=j.indexOf(c),-1!==d&&j.splice(d,1)),e.isArray(k)&&(d=k.indexOf(c),-1===d&&k.push(c))),f&&this.qn(c,g),void(h&&this.rn(c)))}),c.prototype.rn=function(a){for(var b,c=0;c<this.kn.length;c++)if(this.kn[c].sn===a){b=this.kn[c],b.id&&clearTimeout(b.id),this.kn.splice(c,1);break}},c.prototype.qn=function(a,b){var c;if(b){for(var d=0;d<this.kn.length;d++)if(this.kn[d].sn===a){c=this.kn[d];break}}else c={sn:a,Be:0,tn:function(b){c.Be++,a.ping(function(c){a.Zm(c?"dead":"alive"),b&&"function"==typeof b&&b(c)})}},this.kn.push(c);c.id&&clearTimeout(c.id);var f=this.fn(c.Be,this.dn);c.id=setTimeout(c.tn,f),c.un=e.now()+f},c.prototype.nn=function(a){var b=e.$d(this.kn,"runAt"),c=this.log;d.i(function e(){var f=b.shift();return f?f.sn?void("dead"===f.sn.status?f.tn(function(b){b?(c.vn("Unable to revive connection: "+f.sn.id),d.i(e)):a(void 0,f.sn)}):a(void 0,f.sn)):void e():void a(void 0)})},c.prototype.wn=function(a,b){var c;return c=a?this.hn[a]:this.hn[this.hn.in.length?"in":"jn"],null==b?c.slice(0):e.Zd(c).slice(0,b)},c.prototype.xn=function(a){a.id||(a.id=""+a.host),this.index[a.id]||(this.log.info("Adding connection to",a.id),this.index[a.id]=a,a.aa("status set",this.bound.on),a.Zm("alive"))},c.prototype.yn=function(a){a.id||(a.id=""+a.host),this.index[a.id]&&(delete this.index[a.id],a.Zm("closed"),a.removeListener("status set",this.bound.on))},c.prototype.zn=function(a){var b,c,d,f,g=e.clone(this.index);for(c=0;c<a.length;c++)f=a[c],d=""+f,this.index[d]?delete g[d]:(b=new this.lm(f,this._m),b.id=d,this.xn(b));var h=e.keys(g);for(c=0;c<h.length;c++)this.yn(this.index[h[c]])},c.prototype.An=function(){return e.values(this.index).map(function(a){return a.host})},c.prototype.close=function(){this.zn([])},c.prototype.empty=c.prototype.close},{xm:32,Am:36,Em:41,Hm:50,k:16}],32:[function(a,b){var c={Bn:a("./xhr"),Cn:a("./jquery"),Dn:a("./angular")},d=a("../utils");d.xe(c,function(a,b){"function"!=typeof a&&delete c[b]}),c.Bn?c.Hl="xhr":c.Dn?c.Hl="angular":c.Hl="jquery",b.g=c},{ll:50,En:11,Fn:11,Gn:33}],33:[function(a,b){function c(a,b){e.call(this,a,b)}b.g=c;var d=a("../utils"),e=a("../connection"),f=a("../errors").Hn,g=!(navigator&&/PhantomJS/i.test(navigator.userAgent));d.H(c,e);var h=d._e;if(h="undefined"!=typeof XMLHttpRequest?function(){return new XMLHttpRequest}:d(["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"]).map(function(a){try{new window.ActiveXObject(a);return function(){return new window.ActiveXObject(a)}}catch(a){return!1}}).compact().Me(),!h)throw Error("getXhr(): XMLHttpRequest not available");c.prototype.nl=function(a,b){var c,d=h(),e=this.host,i=this.log,j=e.In(a),k=e.Jn(a.headers),l=a.async===!1?!1:g;if(d.open(a.method||"GET",j,l),k)for(var m in k)void 0!==k[m]&&d.setRequestHeader(m,k[m]);return d.onreadystatechange=function(){if(4===d.readyState){clearTimeout(c),i.trace(a.method,j,a.body,d.responseText,d.status);var e=d.status?void 0:new f(d.statusText||"Request failed to complete.");b(e,d.responseText,d.status)}},d.send(a.body||void 0),function(){d.abort()}}},{Kn:30,Ln:34,ll:50}],34:[function(a,b){function c(a,b,c){this.message=a,Error.call(this,this.message),g?Error.captureStackTrace(this,b):h?this.stack=Error().stack:this.stack="",c&&(d.assign(this,c),this.toString=function(){return a+" :: "+JSON.stringify(c)},this.toJSON=function(){return d.assign({Mn:a},c)})}var d=a("./utils"),e=a("querystring"),f=b.g,g="function"==typeof Error.captureStackTrace,h=!!Error().stack;f.Nn=c,d.H(c,Error),f.Hn=function(a){c.call(this,a||"Connection Failure",f.Hn)},d.H(f.Hn,c),f.On=function(a){c.call(this,a||"No Living connections",f.On)},d.H(f.On,c),f.Pn=function(a,b){c.call(this,a||"Generic Error",f.Pn,b)},d.H(f.Pn,c),f.Ym=function(a){c.call(this,a||"Request Timeout",f.Ym)},d.H(f.Ym,c),f.Qn=function(a){c.call(this,a||"Unable to parse/serialize body",f.Qn)},d.H(f.Qn,c),f.Rn=function(a){c.call(this,"Cross-domain AJAX requests "+a+" are not supported",f.Rn)},d.H(f.Rn,c);var i=[[300,"Multiple Choices"],[301,"Moved Permanently"],[302,"Found"],[303,"See Other"],[304,"Not Modified"],[305,"Use Proxy"],[307,"Temporary Redirect"],[308,"Permanent Redirect"],[400,"Bad Request"],[401,"Authentication Exception"],[402,"Payment Required"],[403,["Authorization Exception","Forbidden"]],[404,"Not Found"],[405,"Method Not Allowed"],[406,"Not Acceptable"],[407,"Proxy Authentication Required"],[408,"Request Timeout"],[409,"Conflict"],[410,"Gone"],[411,"Length Required"],[412,"Precondition Failed"],[413,"Request Entity Too Large"],[414,"Request URIToo Long"],[415,"Unsupported Media Type"],[416,"Requested Range Not Satisfiable"],[417,"Expectation Failed"],[418,"Im ATeapot"],[421,"Too Many Connections From This IP"],[426,"Upgrade Required"],[429,"Too Many Requests"],[450,"Blocked By Windows Parental Controls"],[494,"Request Header Too Large"],[497,"HTTPTo HTTPS"],[499,"Client Closed Request"],[500,"Internal Server Error"],[501,"Not Implemented"],[502,"Bad Gateway"],[503,"Service Unavailable"],[504,"Gateway Timeout"],[505,"HTTPVersion Not Supported"],[506,"Variant Also Negotiates"],[510,"Not Extended"]];d.xe(i,function(a){function b(a,f){this.status=g,this.Sn=k;var h=null;return d.Ue(a)&&(h=a,a=null),h?(a=[].concat(h.root_cause||[]).reduce(function(a,b){a&&(a+=" (and) "),a+="["+b.type+"] "+b.reason;var c=d.Md(b,["type","reason"]);return d.size(c)&&(a+=", with { "+e.stringify(c," ","=",{encodeURIComponent:function(a){return(a+"").split("\n").join("\\n")}})+" }"),a},""),a||(h.type&&(a+="["+h.type+"] "),h.reason&&(a+=h.reason)),c.call(this,a||j,b,f),this):(c.call(this,a||j,b),this)}var g=a[0],h=a[1],i=[].concat(h,g),j=i[0],k=d.Tn(j);i=d.le(i.concat(k)),d.H(b,c),i.forEach(function(a){f[a]=b})})},{Hm:50,Ka:8}],35:[function(a,b){function c(a,b){if(a=i.clone(a||{}),b=b||{},this.protocol="http",this.host="localhost",this.path="",this.port=9200,this.ua=null,this.headers=null,this.Un=!!b.Un,this.Vn=i.Qc({},a.Vn||{},b.Vn||{},n),"string"==typeof a){var d=a.indexOf(":"),e=a.indexOf("/"),o=-1===e,p=d>-1&&o,q=!p&&e>d;if((o||p||q)&&!j.test(a)&&(a=k+"//"+a),a=i.Rc(g.parse(a,!1,!0),l),!a.port){var r=a.protocol||"http";":"===r.charAt(r.length-1)&&(r=r.substring(0,r.length-1)),c.Wn[r]&&(a.port=c.Wn[r])}}i.F(a)?i.xe(m,function(b){var c=b+"name";a[c]&&a[b]?0===a[b].indexOf(a[c])&&(a[b]=a[c]):a[c]&&(a[b]=a[c]),delete a[c]}):a={},a.ta&&(a.headers=a.headers||{},a.headers.Xn="Basic "+f(a.ta),delete a.ta),i.td(a,function(a,b){null!=a&&(this[b]=i.clone(a))},this),null===this.ua?this.ua={}:i.Ue(this.ua)||(this.ua=h.parse(this.ua)),i.Um(this.port)?this.port=parseInt(this.port,10):this.port=9200,"/"===this.path?this.path="":this.path&&"/"!==this.path.charAt(0)&&(this.path="/"+(this.path||"")),":"===this.protocol.substr(-1)&&(this.protocol=this.protocol.substring(0,this.protocol.length-1))}function d(a,b){return function(c){b&&(c=b.call(this,c));var d=this[a];return d||c?(c&&(d=i.assign({},d,c)),i.size(d)?d:null):null}}var e=a("__browserify_Buffer").na;b.g=c;var f,g=a("url"),h=a("querystring"),i=a("./utils"),j=/^([a-z]+:)?\/\//,k="http:";"undefined"!=typeof window&&void 0!==window.location&&(k=window.location.protocol,f=window.btoa),f=f||function(a){return new e(a,"utf8").toString("base64")};var l=["protocol","hostname","pathname","port","auth","query"],m=["host","path"],n={Yn:null,key:null,Zn:null,$n:null,_n:null,ao:null,bo:!1,co:null};c.Wn={za:80,Aa:443},c.prototype.In=function(a){a=a||{};var b="";this.port!==c.Wn[this.protocol]&&(b=":"+this.port);var d=""+(this.path||"")+(a.path||"");"/"!==d.charAt(0)&&(d="/"+d);var e=h.stringify(this.do(a.ua));return this.host?this.protocol+"://"+this.host+b+d+(e?"?"+e:""):d+(e?"?"+e:"")},c.prototype.Jn=d("headers",function(a){return this.Un?i.Qc(a||{},{eo:"gzip,deflate"}):a}),c.prototype.do=d("query",function(a){return"string"==typeof a?h.parse(a):a}),c.prototype.toString=function(){return this.In()}},{Hm:50,fo:14,Ka:8,url:9}],36:[function(a,b){function c(a){if(a=a||{},a.log){var b,c;if(c=e.isArrayOfStrings(a.log)?[{ho:a.log}]:e.io(a.log,function(a){return e.Ue(a)?a:"string"==typeof a?{level:a}:void 0}),!c)throw new TypeError("Invalid logging output config. Expected either a log level, array of log levels, a logger config object, or an array of logger config objects.");for(b=0;b<c.length;b++)this.jo(c[b])}}var d=a("__browserify_process"),e=a("./utils"),f=a("url"),g=a("events").X;e.H(c,g),c.hm=a("./loggers"),c.prototype.close=function(){this.$("closing"),this.ea()&&(console.error("Something is still listening for log events, but the logger is closing."),this.clearAllListeners())},g.prototype.ea?c.prototype.ea=g.prototype.ea:g.ea?c.prototype.ea=function(a){return g.ea(this,a)}:c.prototype.ea=function(a){return this.da(a).length},c.ho=["error","warning","info","debug","trace"],c.ko=function(a){switch(typeof a){case"string":var b=e.indexOf(c.ho,a);if(b>=0)return c.ho.slice(0,b+1);case"object":if(e.isArray(a)){var d=e.zd(a,c.ho);if(d.length===a.length)return d}default:throw new TypeError("invalid logging level "+a+". Expected zero or more of these options: "+c.ho.join(", "))}},c.join=function(a){return e.map(a,function(a){return e.Ue(a)?e.Ta(a)+"\n":""+a}).join(" ")},c.prototype.jo=function(a){a=a||{},a.ho=c.ko(a.ho||a.level||"warning"),delete a.level;var b=e.dm(a,"type",c.hm,d.dh?"console":"stdio");return new b(this,a)},c.prototype.error=function(a){return this.ea("error")?this.$("error",a instanceof Error?a:Error(a)):void 0},c.prototype.vn=function(){return this.ea("warning")?this.$("warning",c.join(arguments)):void 0},c.prototype.info=function(){return this.ea("info")?this.$("info",c.join(arguments)):void 0},c.prototype.debug=function(){return this.ea("debug")?this.$("debug",c.join(arguments)):void 0},c.prototype.trace=function(a,b,d,e,f){return this.ea("trace")?this.$("trace",c.lo(a,b,d,e,f)):void 0},c.lo=function(a,b,c,d,g){return"string"==typeof b?b=f.parse(b,!0,!0):(b=e.clone(b),b.path&&(b.ua=f.parse(b.path,!0,!1).ua),!b.pathname&&b.path&&(b.pathname=b.path.split("?").shift())),delete b.ta,{method:a,url:f.format(b),body:c,status:g,response:d}},b.g=c},{Cm:38,Hm:50,k:16,$m:6,url:9}],37:[function(a,b){function c(a,b){this.log=a,this.mo=[],f.Xm(this),this.log.ba("closing",this.bound.no),this.oo(b.ho)}function d(a){return 10>a?"0"+a.toString(10):a.toString(10)}function e(a,b){var c=f.repeat(" ",b||2);return(a||"").split(/\r?\n/).map(function(a){return c+a}).join("\n")}var f=a("./utils");c.prototype.timestamp=function(){var a=new Date;return a.getUTCFullYear()+"-"+d(a.getUTCMonth()+1)+"-"+d(a.getUTCDate())+"T"+d(a.getUTCHours())+":"+d(a.getUTCMinutes())+":"+d(a.getUTCSeconds())+"Z"},c.prototype.format=function(a,b){return a+": "+this.timestamp()+"\n"+e(b)+"\n\n"},c.prototype.write=function(){throw Error("This should be overwritten by the logger")},c.prototype.oo=function(a){this.no(),this.mo=[],f.xe(a,function(a){var b="on"+f.po(a);if(!this.bound[b])throw Error('Unable to listen for level "'+a+'"');this.mo.push(a),this.log.aa(a,this.bound[b])},this)},c.prototype.no=f.pn(function(){f.xe(this.mo,function(a){this.log.removeListener(a,this.bound["on"+f.po(a)])},this)}),c.prototype.qo=f.pn(function(a){this.write("Error"===a.name?"ERROR":a.name,a.stack)}),c.prototype.ro=f.pn(function(a){this.write("WARNING",a)}),c.prototype.so=f.pn(function(a){this.write("INFO",a)}),c.prototype.to=f.pn(function(a){this.write("DEBUG",a)}),c.prototype.uo=f.pn(function(a){this.write("TRACE",this.vo(a))}),c.prototype.vo=function(a){return"-> "+a.method+" "+a.url+"\n"+this.wo(a.body)+"\n<- "+a.status+"\n"+this.wo(a.response)},c.prototype.wo=function(a){try{return"string"==typeof a&&(a=JSON.parse(a)),JSON.stringify(a,null," ").replace(/'/g,"\\u0027")}catch(b){return"string"==typeof a?a:""}},b.g=c},{Hm:50}],38:[function(a,b){b.g={console:a("./console")}},{xo:39}],39:[function(a,b){function c(a,b){d.call(this,a,b),this.color=e.has(b,"color")?!!b.color:!0}b.g=c;var d=a("../logger"),e=a("../utils");e.H(c,d),c.prototype.oo=function(a){d.prototype.oo.call(this,a)},c.prototype.write=function(a,b,c){console[c]&&console[c](this.format(a,b))},c.prototype.qo=e.pn(function(a){var b=console.error?"error":"log";this.write("Error"===a.name?"ERROR":a.name,a.stack||a.message,b)}),c.prototype.ro=e.pn(function(a){this.write("WARNING",a,console.warn?"warn":"log")}),c.prototype.so=e.pn(function(a){this.write("INFO",a,console.info?"info":"log")}),c.prototype.to=e.pn(function(a){this.write("DEBUG",a,console.debug?"debug":"log")}),c.prototype.uo=e.pn(function(a){this.write("TRACE",this.vo(a),"log")})},{yo:37,ll:50}],40:[function(a,b){function c(a){return function(b){return d.transform(b,function(b,c,d){var f=c[a];if(f){var g={host:void 0,port:void 0,zo:{id:d,name:c.name,hostname:c.hostname,version:c.version}},h=Error("Malformed "+a+". Got "+JSON.stringify(c[a])+' and expected it to match "{hostname?}/{ip}:{port}".'),i=e.exec(f);if(i)return g.host=i[1],g.port=parseInt(i[2],10),void b.push(g);if(f.indexOf("/")>-1){var j=f.split("/");if(2!==j.length)throw h;g.host=j.shift(),f=j.shift()}if(f.indexOf(":")<0)throw h;var k=f.split(":");if(2!==k.length)throw h;g.host=g.host||k[0],g.port=parseInt(k[1],10),b.push(g)}},[])}}var d=a("./utils"),e=/\[\/*([^:]+):(\d+)\]/;b.g=c("http_address"),b.g.Ao=c("transport_address")},{Hm:50}],41:[function(a,b){b.g={random:a("./random"),Bo:a("./round_robin")}},{Co:42,Do:43}],42:[function(a,b){b.g=function(a){return a[Math.floor(Math.random()*a.length)]}},{}],43:[function(a,b){b.g=function(a){var b=a[0];return a.push(a.shift()),b}},{}],44:[function(a,b){function c(){}var d=a("../utils"),e=a("../serializers/json");d.H(c,e),c.prototype.encode=function(a){switch(typeof a){case"string":return a;case"object":if(a)return angular.toJson(a);default:return}},b.g=c},{Eo:46,ll:50}],45:[function(a,b){b.g={Dn:a("./angular"),json:a("./json")}},{En:44,Fo:46}],46:[function(a,b){function c(){}b.g=c;var d=a("../utils");c.prototype.Go=function(a,b,c){switch(typeof a){case"string":return a;case"object":if(a)return JSON.stringify(a,b,c);default:return}},c.prototype.Go.contentType="application/json",c.prototype.Ho=function(a){if("string"==typeof a)try{return JSON.parse(a)}catch(a){}},c.prototype.Ph=function(a){var b,c="";if(d.isArray(a))for(b=0;b<a.length;b++)c+=this.Go(a[b])+"\n";else{if("string"!=typeof a)throw new TypeError("Bulk body should either be an Array of commands/string, or a String");c=a+("\n"===a[a.length-1]?"":"\n")}return c},c.prototype.Ph.contentType="application/x-ldjson"},{ll:50}],47:[function(a,b){function c(b){var d=this;b=d._m=b||{};var f="function"==typeof b.log?b.log:a("./log");b.log=d.log=new f(b);var h=e.dm(b,"connectionPool",c.Io,"main");d.Jo=new h(b);var k=e.dm(b,"serializer",c.jm,"json");d.Ko=new k(b),d.Lo=e.dm(b,"nodesToHostCallback",c.Mo,"main"),d.No=b.hasOwnProperty("maxRetries")?b.No:3,d.fm=b.hasOwnProperty("sniffEndpoint")?b.fm:"/_nodes/_all/clear",d.Ok=b.hasOwnProperty("requestTimeout")?b.Ok:3e4,b.hasOwnProperty("defer")&&(d.defer=b.defer);var l=b.hasOwnProperty("randomizeHosts")?!!b.randomizeHosts:!0;if(b.host&&(b._l=b.host),b._l){var m=e.io(b._l,function(a){return e.Ue(a)||e.u(a)||a instanceof g?a:void 0});if(!m)throw new TypeError("Invalid hosts config. Expected a URL, an array of urls, a host config object, or an array of host config objects.");l&&(m=e.Zd(m)),d.zn(m)}b.hasOwnProperty("sniffedNodesProtocol")?d.Oo=b.Oo||null:d.Oo=j(d.Jo.An())||null,b.sniffOnStart&&d.Po(),b.sniffInterval&&d.Qo(function a(){d.Po(),d.Qo(a,b.sniffInterval)},b.sniffInterval),b.sniffOnConnectionFault&&i(d)}var d=a("__browserify_process");b.g=c;var e=a("./utils"),f=a("./errors"),g=a("./host"),h=a("promise/lib/es6-extensions"),i=a("./transport/sniff_on_connection_fault"),j=a("./transport/find_common_protocol");c.Io={Ro:a("./connection_pool")},c.jm=a("./serializers"),c.Mo={Ro:a("./nodes_to_host")},c.prototype.defer=function(){var a={};return a.ph=new h(function(b,c){a.resolve=b,a.reject=c}),a},c.prototype.nl=function(a,b){function c(b,c){r||(b?h(b):c?(j=c,k=j.nl(a.Nh,g)):(o.log.vn("No living connections"),h(new f.On)))}function g(b,d,e,g){if(!r){if(k=void 0,b instanceof f.Rn)return o.log.error("Connection refused to execute the request",b),void h(b,d,e,g);if(b){j.Zm("dead");var i=b.message||"";i="\n"+a.Nh.method+" "+j.host.In(a.Nh)+(i.length?" => ":"")+i,p?(p--,o.log.error("Request error, retrying"+i),o.Jo.select(c)):(o.log.error("Request complete with error"+i),h(new f.Hn(b)))}else o.log.debug("Request complete"),h(void 0,d,e,g)}}function h(c,d,g,h){if(!r){o.Qo(l);var i,j=!h||h["So"]&&~h["So"].indexOf("application/json");if(!c&&d&&(j?(i=o.Ko.Ho(d),null==i&&(c=new f.Qn,i=d)):i=d),(!c||c instanceof f.Qn)&&(200>g||g>=300)&&(!a.Om||!e.contains(a.Om,g))){var k=e.Rc(a.Nh,["path","query","body"]);k.To=g,k.response=d,401===g&&h&&h["Uo"]&&(k.Vo=h["Uo"]),c=f[g]?new f[g](i&&i.error,k):new f.Pn("unknown error",k)}a.Lm&&(c&&c instanceof f.NotFound?(i=!1,c=void 0):i=!c),"function"==typeof b?c?b(c,i,g):b(void 0,i,g):c?(c.body=i,c.status=g,n.reject(c)):n.resolve(i)}}function i(){r||(r=!0,p=0,o.Qo(l),"function"==typeof k&&k())}var j,k,l,m,n,o=this,p=this.No,q=this.Ok,r=!1,s=a.body,t=a.headers?e.transform(a.headers,function(a,b,c){a[(c+"").toLowerCase()]=b}):{};if(o.log.debug("starting request",a),"function"==typeof b?(d.domain&&(b=d.domain.bind(b)),m={abort:i}):(n=this.defer(),m=n.ph,m.abort=i),s&&"GET"===a.method)return e.i(h,new TypeError('Body can not be sent with method "GET"')),m;if(s){var u=o.Ko,v=u[a.Ph?"Ph":"Go"];s=v.call(u,s),t["So"]||(t["So"]=v.contentType)}return a.hasOwnProperty("maxRetries")&&(p=a.No),a.hasOwnProperty("requestTimeout")&&(q=a.Ok),a.Nh={method:a.method,path:a.path||"/",ua:a.ua,body:s,headers:t},q&&q!==1/0&&(l=this.Qo(function(){h(new f.Ym("Request Timeout after "+q+"ms")),i()},q)),j?c(void 0,j):o.Jo.select(c),m},c.prototype.Qo=function(a,b){if(!this.closed){var c,d=this.Wo||(this.Wo=[]);if("function"!=typeof a&&(c=a,a=void 0),a)return c=setTimeout(function(){e.Ud(d,c),a()},b),d.push(c),c;if(c){clearTimeout(c);var f=this.Wo.indexOf(c);-1!==f&&this.Wo.splice(f,1)}}},c.prototype.Po=function(a){var b=this,c=this.Lo,d=this.log,f=this.Oo;a="function"==typeof a?a:e._e,this.nl({path:this.fm,method:"GET"},function(g,h,i){if(!g&&h&&h.ei){var j;
try{j=c(h.ei)}catch(a){return void d.error(Error("Unable to convert node list from "+this.fm+" to hosts durring sniff. Encountered error:\n"+(a.stack||a.message)))}e.forEach(j,function(a){f&&(a.protocol=f)}),b.zn(j)}a(g,h,i)})},c.prototype.zn=function(a){var b=this._m;this.Jo.zn(e.map(a,function(a){return a instanceof g?a:new g(a,b)}))},c.prototype.close=function(){this.log.close(),this.closed=!0,e.xe(this.Wo,clearTimeout),this.Wo=null,this.Jo.close()}},{wm:31,ym:34,zm:35,Am:36,Dm:40,Fm:45,Xo:48,Yo:49,Hm:50,k:16,Zo:18}],48:[function(a,b){var c=a("lodash").Re;b.g=function(a){if(c(a))return!1;for(var b=a.shift().protocol,d=0;d<a.length;d++)if(b!==a[d].protocol)return!1;return b}},{$o:15}],49:[function(a,b){var c=a("../utils");b.g=function(a){var b=0,d=a.Jo,e=d.qn,f=function(){f._o=a.Qo(f._o),a.Po()},g=function(a){var b=c.now();return function(){return b-a}};d.qn=function(c,h){var i=e.call(d,c,h);b=f._o?b+1:0;var j=d.fn(b,1e3);return f._o&&j<f._o&&f.ap()&&(f._o=a.Qo(f._o)),f._o||(f._o=a.Qo(f,j),f.ap=g(j)),i},d.qn.restore=function(){d.qn=e}}},{ll:50}],50:[function(a,b){function c(a,b,c){return function(d){for(var e,f,g,h,i=0,j=[],k="";i<d.length;i++)e=d.charCodeAt(i),f=d.charAt(i),h=e>=97&&122>=e||e>=48&&57>=e,g=e>=65&&90>=e,!g&&h||(k.length&&j.push(k),k=""),(g||h)&&(h&&k.length?k+=f:k=!j.length&&a||j.length&&b?f.toUpperCase():f.toLowerCase());return k.length&&j.push(k),j.length&&"_"===d.charAt(0)&&(j[0]="_"+j[0]),j.join(c)}}var d=a("__browserify_process"),e=a("__browserify_Buffer").na,f=a("path"),g=a("lodash"),h=a("util"),i=g.extend({},g,h);g=i,i.bp=f.join,i.cp=function(a,b){return g.xe(b,function(c,d){switch(typeof a[d]){case"undefined":a[d]=b[d];break;case"object":g.isArray(a[d])&&g.isArray(b[d])?a[d]=a[d].concat(b[d]):g.Ue(a[d])&&g.Ue(b[d])&&i.cp(a[d],b[d])}}),a},g.xe(["String","Object","PlainObject","Array","Finite","Function","RegExp"],function(a){var b=g["is"+a];i["isArrayOf"+a+"s"]=function(a){return g.isArray(a)&&g.every(a.slice(0,10),b)}}),i.po=function(a){return a[0].toUpperCase()+a.substring(1).toLowerCase()},i.Tn=c(!0,!0,""),i.Ce=c(!1,!0,""),i.df=c(!1,!1,"_"),i.dp=function(a){return a?"string"!=typeof a&&(a=""+a):a="",a.toLowerCase()},i.Pm=function(a){return a?"string"!=typeof a&&(a=""+a):a="",a.toUpperCase()},i.Um=function(a){return"object"!=typeof a&&a-parseFloat(a)>=0};var j=/^(\d+(?:\.\d+)?)(M|w|d|h|m|s|y|ms)$/;i.Vm=function(a){return!(!a.match||!a.match(j))},i.repeat=function(a,b){return Array(b+1).join(a)},i.ep=function(a,b,c,d){switch(d=d||0,c.length-d){case 0:return a.call(b);case 1:return a.call(b,c[0+d]);case 2:return a.call(b,c[0+d],c[1+d]);case 3:return a.call(b,c[0+d],c[1+d],c[2+d]);case 4:return a.call(b,c[0+d],c[1+d],c[2+d],c[3+d]);case 5:return a.call(b,c[0+d],c[1+d],c[2+d],c[3+d],c[4+d]);default:return a.apply(b,Array.prototype.slice.call(c,d))}},g.i=function(a){d.i(g.Yc(g,"applyArgs",a,null,arguments,1))},g.pn=function(a){return a.fp=!0,a},g.gp=g.pn,g.Xm=function(a){a.bound={};for(var b in a)"function"==typeof a[b]&&a[b].fp===!0&&(a.bound[b]=g.bind(a[b],a))},g._e=function(){},g.dm=function(a,b,c,d){var e=a[b];switch(typeof e){case"undefined":return c[d];case"function":return e;case"string":if(c.hasOwnProperty(e))return c[e];default:var f="Invalid "+b+' "'+e+'", expected a function';switch(g.size(c)){case 0:break;case 1:f+=" or "+g.keys(c)[0];break;default:f+=" or one of "+g.keys(c).join(", ")}throw new TypeError(f)}},g.io=function(a,b){b="function"==typeof b?b:g.identity;var c,d,e=[];for(g.isArray(a)||(a=[a]),d=0;d<a.length;d++){if(c=b(a[d]),void 0===c)return!1;e.push(c)}return e},g.hp=function(a){var b=g.ip(a);if(b){var c="";return b.length?(g.xe(b,function(a){if(a.Zc)c+=""+a.Zc;else{if(!g.isArray(a)||"string"!=typeof a[0]&&!e.isBuffer(a[0]))return!1;c+=""+a[0]}}),c):c}},g.ip=function(a){if(a&&a._writableState){var b=a._writableState;return b.getBuffer?b.getBuffer():b.buffer?b.buffer:void 0}},g.jp=function(a){var b=g.ip(a);return b&&b.splice(0)},g.now=function(){return"function"==typeof Date.now?Date.now():(new Date).getTime()},b.g=i},{fo:14,k:16,$o:15,path:7,U:10}]},{},[19])(19)});
}()); | sufuf3/cdnjs | ajax/libs/elasticsearch/11.0.0/elasticsearch.min.js | JavaScript | mit | 388,493 |
/*!
* json-schema-faker library v0.2.13
* http://json-schema-faker.js.org
* @preserve
*
* Copyright (c) 2014-2016 Alvaro Cabrera & Tomasz Ducin
* Released under the MIT license
*
* Date: 2016-03-21 17:27:39.965Z
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsf = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Generates randomized boolean value.
*
* @returns {boolean}
*/
module.exports = function() {
return Math.random() > 0.5;
};
},{}],2:[function(require,module,exports){
/**
* Generates null value.
*
* @returns {null}
*/
module.exports = function() {
return null;
};
},{}],3:[function(require,module,exports){
var random = require('./../util/random');
var LIPSUM_WORDS = ('Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore'
+ ' et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea'
+ ' commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla'
+ ' pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est'
+ ' laborum').split(' ');
/**
* Generates randomized array of single lorem ipsum words.
*
* @param min
* @param max
* @returns {Array.<string>}
*/
module.exports = function(min, max) {
var words = random.shuffle(LIPSUM_WORDS),
length = random(min || 1, Math.min(LIPSUM_WORDS.length, max || min || 5));
return words.slice(0, length);
};
},{"./../util/random":17}],4:[function(require,module,exports){
var container = require('./util/container'),
traverse = require('./util/traverse'),
formats = require('./util/formats'),
random = require('./util/random'),
merge = require('./util/merge');
var deref = require('deref');
function isKey(prop) {
return prop === 'enum' || prop === 'required' || prop === 'definitions';
}
function generate(schema, refs, ex) {
var $ = deref();
try {
var seen = {};
return traverse($(schema, refs, ex), [], function reduce(sub) {
if (seen[sub.$ref] <= 0) {
delete sub.$ref;
delete sub.oneOf;
delete sub.anyOf;
delete sub.allOf;
return sub;
}
if (typeof sub.$ref === 'string') {
var id = sub.$ref;
delete sub.$ref;
if (!seen[id]) {
// TODO: this should be configurable
seen[id] = random(1, 5);
}
seen[id] -= 1;
merge(sub, $.util.findByRef(id, $.refs));
}
if (Array.isArray(sub.allOf)) {
var schemas = sub.allOf;
delete sub.allOf;
// this is the only case where all sub-schemas
// must be resolved before any merge
schemas.forEach(function(s) {
merge(sub, reduce(s));
});
}
if (Array.isArray(sub.oneOf || sub.anyOf)) {
var mix = sub.oneOf || sub.anyOf;
delete sub.anyOf;
delete sub.oneOf;
merge(sub, random.pick(mix));
}
for (var prop in sub) {
if ((Array.isArray(sub[prop]) || typeof sub[prop] === 'object') && !isKey(prop)) {
sub[prop] = reduce(sub[prop]);
}
}
return sub;
});
} catch (e) {
if (e.path) {
throw new Error(e.message + ' in ' + '/' + e.path.join('/'));
} else {
throw e;
}
}
}
generate.formats = formats;
// returns itself for chaining
generate.extend = function(name, cb) {
container.set(name, cb);
return generate;
};
module.exports = generate;
},{"./util/container":10,"./util/formats":12,"./util/merge":15,"./util/random":17,"./util/traverse":18,"deref":19}],5:[function(require,module,exports){
var random = require('../util/random'),
traverse = require('../util/traverse'),
hasProps = require('../util/has-props');
var ParseError = require('../util/error');
function unique(path, items, value, sample, resolve) {
var tmp = [],
seen = [];
function walk(obj) {
var json = JSON.stringify(obj);
if (seen.indexOf(json) === -1) {
seen.push(json);
tmp.push(obj);
}
}
items.forEach(walk);
// TODO: find a better solution?
var limit = 100;
while (tmp.length !== items.length) {
walk(traverse(value.items || sample, path, resolve));
if (!limit--) {
break;
}
}
return tmp;
}
module.exports = function(value, path, resolve) {
var items = [];
if (!(value.items || value.additionalItems)) {
if (hasProps(value, 'minItems', 'maxItems', 'uniqueItems')) {
throw new ParseError('missing items for ' + JSON.stringify(value), path);
}
return items;
}
if (Array.isArray(value.items)) {
return Array.prototype.concat.apply(items, value.items.map(function(item, key) {
return traverse(item, path.concat(['items', key]), resolve);
}));
}
var length = random(value.minItems, value.maxItems, 1, 5),
sample = typeof value.additionalItems === 'object' ? value.additionalItems : {};
for (var current = items.length; current < length; current += 1) {
items.push(traverse(value.items || sample, path.concat(['items', current]), resolve));
}
if (value.uniqueItems) {
return unique(path.concat(['items']), items, value, sample, resolve);
}
return items;
};
},{"../util/error":11,"../util/has-props":13,"../util/random":17,"../util/traverse":18}],6:[function(require,module,exports){
var number = require('./number');
// The `integer` type is just a wrapper for the `number` type. The `number` type
// returns floating point numbers, and `integer` type truncates the fraction
// part, leaving the result as an integer.
//
module.exports = function(value) {
var generated = number(value);
// whether the generated number is positive or negative, need to use either
// floor (positive) or ceil (negative) function to get rid of the fraction
return generated > 0 ? Math.floor(generated) : Math.ceil(generated);
};
},{"./number":7}],7:[function(require,module,exports){
var MIN_INTEGER = -100000000,
MAX_INTEGER = 100000000;
var random = require('../util/random'),
string = require('./string');
module.exports = function(value) {
if (value.faker || value.chance) {
return string(value);
}
var multipleOf = value.multipleOf;
var min = typeof value.minimum === 'undefined' ? MIN_INTEGER : value.minimum,
max = typeof value.maximum === 'undefined' ? MAX_INTEGER : value.maximum;
if (multipleOf) {
max = Math.floor(max / multipleOf) * multipleOf;
min = Math.ceil(min / multipleOf) * multipleOf;
}
if (value.exclusiveMinimum && value.minimum && min === value.minimum) {
min += multipleOf || 1;
}
if (value.exclusiveMaximum && value.maximum && max === value.maximum) {
max -= multipleOf || 1;
}
if (multipleOf) {
return Math.floor(random(min, max) / multipleOf) * multipleOf;
}
if (min > max) {
return NaN;
}
return random({
min: min,
max: max,
hasPrecision: true
});
};
},{"../util/random":17,"./string":9}],8:[function(require,module,exports){
var container = require('../util/container'),
random = require('../util/random'),
words = require('../generators/words'),
traverse = require('../util/traverse'),
hasProps = require('../util/has-props');
var RandExp = container.get('randexp'),
randexp = RandExp.randexp;
var ParseError = require('../util/error');
module.exports = function(value, path, resolve) {
var props = {};
if (!(value.properties || value.patternProperties || value.additionalProperties)) {
if (hasProps(value, 'minProperties', 'maxProperties', 'dependencies', 'required')) {
throw new ParseError('missing properties for ' + JSON.stringify(value), path);
}
return props;
}
var reqProps = value.required || [],
allProps = value.properties ? Object.keys(value.properties) : [];
reqProps.forEach(function(key) {
if (value.properties && value.properties[key]) {
props[key] = value.properties[key];
}
});
var optProps = allProps.filter(function(prop) {
return reqProps.indexOf(prop) === -1;
});
if (value.patternProperties) {
optProps = Array.prototype.concat.apply(optProps, Object.keys(value.patternProperties));
}
var length = random(value.minProperties, value.maxProperties, 0, optProps.length);
random.shuffle(optProps).slice(0, length).forEach(function(key) {
if (value.properties && value.properties[key]) {
props[key] = value.properties[key];
} else {
props[randexp(key)] = value.patternProperties[key];
}
});
var current = Object.keys(props).length,
sample = typeof value.additionalProperties === 'object' ? value.additionalProperties : {};
if (current < length) {
words(length - current).forEach(function(key) {
props[key + randexp('[a-f\\d]{4,7}')] = sample;
});
}
return traverse(props, path.concat(['properties']), resolve);
};
},{"../generators/words":3,"../util/container":10,"../util/error":11,"../util/has-props":13,"../util/random":17,"../util/traverse":18}],9:[function(require,module,exports){
var container = require('../util/container');
var faker = container.get('faker'),
chance = container.get('chance'),
RandExp = container.get('randexp'),
randexp = RandExp.randexp;
var words = require('../generators/words'),
random = require('../util/random'),
formats = require('../util/formats');
var regexps = {
email: '[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}',
hostname: '[a-zA-Z]{1,33}\\.[a-z]{2,4}',
ipv6: '[abcdef\\d]{4}(:[abcdef\\d]{4}){7}',
uri: '[a-zA-Z][a-zA-Z0-9+-.]*'
};
function get(obj, key) {
var parts = key.split('.');
while (parts.length) {
var prop = parts.shift();
if (!obj[prop]) {
break;
}
obj = obj[prop];
}
return obj;
}
function thunk() {
return words().join(' ');
}
function generate(value) {
if (value.use) {
var args = [],
path = value.key;
if (typeof path === 'object') {
path = Object.keys(path)[0];
if (Array.isArray(value.key[path])) {
args = value.key[path];
} else {
args.push(value.key[path]);
}
}
var gen = get(value.gen, path);
if (typeof gen !== 'function') {
throw new Error('unknown ' + value.use + '-generator for ' + JSON.stringify(value.key));
}
return gen.apply(value.gen, args);
}
switch (value.format) {
case 'date-time':
return new Date(random(0, 100000000000000)).toISOString();
case 'email':
case 'hostname':
case 'ipv6':
case 'uri':
return randexp(regexps[value.format]).replace(/\{(\w+)\}/, function(matches, key) {
return randexp(regexps[key]);
});
case 'ipv4':
return [0, 0, 0, 0].map(function() {
return random(0, 255);
}).join('.');
case 'regex':
// TODO: discuss
return '.+?';
default:
var callback = formats(value.format);
if (typeof callback !== 'function') {
throw new Error('unknown generator for ' + JSON.stringify(value.format));
}
var generators = {
faker: faker,
chance: chance,
randexp: randexp
};
return callback(generators, value);
}
}
module.exports = function(value) {
if (value.faker || value.chance) {
return generate({
use: value.faker ? 'faker' : 'chance',
gen: value.faker ? faker : chance,
key: value.faker || value.chance
});
}
if (value.format) {
return generate(value);
}
if (value.pattern) {
return randexp(value.pattern);
}
var min = Math.max(0, value.minLength || 0),
max = random(min, value.maxLength || 140);
var sample = thunk();
while (sample.length < min) {
sample += thunk();
}
if (sample.length > max) {
sample = sample.substr(0, max);
}
return sample;
};
},{"../generators/words":3,"../util/container":10,"../util/formats":12,"../util/random":17}],10:[function(require,module,exports){
// static requires - handle both initial dependency load (deps will be available
// among other modules) as well as they will be included by browserify AST
var container = {
faker: null,
chance: null,
// randexp is required for "pattern" values
randexp: require('randexp')
};
module.exports = {
set: function(name, callback) {
if (typeof container[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency is not allowed.');
}
container[name] = callback(container[name]);
},
get: function(name) {
if (typeof container[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency doesn\'t exist.');
}
return container[name];
}
};
},{"randexp":169}],11:[function(require,module,exports){
function ParseError(message, path) {
this.message = message;
this.path = path;
this.name = 'ParseError';
}
ParseError.prototype = Error.prototype;
module.exports = ParseError;
},{}],12:[function(require,module,exports){
var registry = {};
module.exports = function(name, callback) {
if (callback) {
registry[name] = callback;
} else if (typeof name === 'object') {
for (var method in name) {
registry[method] = name[method];
}
} else if (name) {
return registry[name];
}
return registry;
};
},{}],13:[function(require,module,exports){
module.exports = function(obj) {
return Array.prototype.slice.call(arguments, 1).filter(function(key) {
return typeof obj[key] !== 'undefined';
}).length > 0;
};
},{}],14:[function(require,module,exports){
var inferredProperties = {
array: [
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems'
],
integer: [
'exclusiveMaximum',
'exclusiveMinimum',
'maximum',
'minimum',
'multipleOf'
],
object: [
'additionalProperties',
'dependencies',
'maxProperties',
'minProperties',
'patternProperties',
'properties',
'required'
],
string: [
'maxLength',
'minLength',
'pattern'
]
};
inferredProperties.number = inferredProperties.integer;
var subschemaProperties = [
'additionalItems',
'items',
'additionalProperties',
'dependencies',
'patternProperties',
'properties'
];
/**
* Iterates through all keys of `obj` and:
* - checks whether those keys match properties of a given inferred type
* - makes sure that `obj` is not a subschema; _Do not attempt to infer properties named as subschema containers. The
* reason for this is that any property name within those containers that matches one of the properties used for
* inferring missing type values causes the container itself to get processed which leads to invalid output. (Issue 62)_
*
* @returns {boolean}
*/
function matchesType(obj, lastElementInPath, inferredTypeProperties) {
return Object.keys(obj).filter(function(prop) {
var isSubschema = subschemaProperties.indexOf(lastElementInPath) > -1,
inferredPropertyFound = inferredTypeProperties.indexOf(prop) > -1;
if (inferredPropertyFound && !isSubschema) {
return true;
}
}).length > 0;
}
/**
* Checks whether given `obj` type might be inferred. The mechanism iterates through all inferred types definitions,
* tries to match allowed properties with properties of given `obj`. Returns type name, if inferred, or null.
*
* @returns {string|null}
*/
module.exports = function(obj, schemaPath) {
for (var typeName in inferredProperties) {
var lastElementInPath = schemaPath[schemaPath.length - 1];
if (matchesType(obj, lastElementInPath, inferredProperties[typeName])) {
return typeName;
}
}
};
},{}],15:[function(require,module,exports){
function clone(arr) {
var out = [];
arr.forEach(function(item, index) {
if (typeof item === 'object' && item !== null) {
out[index] = Array.isArray(item) ? clone(item) : merge({}, item);
} else {
out[index] = item;
}
});
return out;
}
function merge(a, b) {
for (var key in b) {
if (typeof b[key] !== 'object' || b[key] === null) {
a[key] = b[key];
} else if (Array.isArray(b[key])) {
a[key] = (a[key] || []).concat(clone(b[key]));
} else if (typeof a[key] !== 'object' || a[key] === null || Array.isArray(a[key])) {
a[key] = merge({}, b[key]);
} else {
a[key] = merge(a[key], b[key]);
}
}
return a;
}
module.exports = merge;
},{}],16:[function(require,module,exports){
module.exports = {
boolean: require('../generators/boolean'),
null: require('../generators/null'),
array: require('../types/array'),
integer: require('../types/integer'),
number: require('../types/number'),
object: require('../types/object'),
string: require('../types/string')
};
},{"../generators/boolean":1,"../generators/null":2,"../types/array":5,"../types/integer":6,"../types/number":7,"../types/object":8,"../types/string":9}],17:[function(require,module,exports){
function random(min, max, defMin, defMax) {
var hasPrecision = false;
if (typeof min === 'object') {
hasPrecision = min.hasPrecision;
max = min.max;
defMin = min.defMin;
defMax = min.defMax;
min = min.min;
}
defMin = typeof defMin === 'undefined' ? random.MIN_NUMBER : defMin;
defMax = typeof defMax === 'undefined' ? random.MAX_NUMBER : defMax;
min = typeof min === 'undefined' ? defMin : min;
max = typeof max === 'undefined' ? defMax : max;
if (max < min) {
max += min;
}
var number = Math.random() * (max - min) + min;
if (!hasPrecision) {
return parseInt(number, 10);
}
return number;
};
random.shuffle = function(obj) {
var copy = obj.slice(),
length = obj.length;
for (; length > 0;) {
var key = Math.floor(Math.random() * length),
tmp = copy[--length];
copy[length] = copy[key];
copy[key] = tmp;
}
return copy;
};
random.pick = function(obj) {
return obj[Math.floor(Math.random() * obj.length)];
};
random.MIN_NUMBER = -100;
random.MAX_NUMBER = 100;
module.exports = random;
},{}],18:[function(require,module,exports){
var random = require('./random');
var ParseError = require('./error');
var inferredType = require('./inferred');
var primitives = null;
function traverse(obj, path, resolve) {
resolve(obj);
var copy = {};
if (Array.isArray(obj)) {
copy = [];
}
if (Array.isArray(obj.enum)) {
return random.pick(obj.enum);
}
var type = obj.type;
if (Array.isArray(type)) {
type = random.pick(type);
} else if (typeof type === 'undefined') {
// Attempt to infer the type
type = inferredType(obj, path) || type;
}
if (typeof type === 'string') {
if (!primitives[type]) {
throw new ParseError('unknown primitive ' + JSON.stringify(type), path.concat(['type']));
}
try {
return primitives[type](obj, path, resolve);
} catch (e) {
if (typeof e.path === 'undefined') {
throw new ParseError(e.message, path);
}
throw e;
}
}
for (var prop in obj) {
if (typeof obj[prop] === 'object' && prop !== 'definitions') {
copy[prop] = traverse(obj[prop], path.concat([prop]), resolve);
} else {
copy[prop] = obj[prop];
}
}
return copy;
}
module.exports = function() {
primitives = primitives || require('./primitives');
return traverse.apply(null, arguments);
};
},{"./error":11,"./inferred":14,"./primitives":16,"./random":17}],19:[function(require,module,exports){
'use strict';
var $ = require('./util/uri-helpers');
$.findByRef = require('./util/find-reference');
$.resolveSchema = require('./util/resolve-schema');
$.normalizeSchema = require('./util/normalize-schema');
var instance = module.exports = function() {
function $ref(fakeroot, schema, refs, ex) {
if (typeof fakeroot === 'object') {
ex = refs;
refs = schema;
schema = fakeroot;
fakeroot = undefined;
}
if (typeof schema !== 'object') {
throw new Error('schema must be an object');
}
if (typeof refs === 'object' && refs !== null) {
var aux = refs;
refs = [];
for (var k in aux) {
aux[k].id = aux[k].id || k;
refs.push(aux[k]);
}
}
if (typeof refs !== 'undefined' && !Array.isArray(refs)) {
ex = !!refs;
refs = [];
}
function push(ref) {
if (typeof ref.id === 'string') {
var id = $.resolveURL(fakeroot, ref.id).replace(/\/#?$/, '');
if (id.indexOf('#') > -1) {
var parts = id.split('#');
if (parts[1].charAt() === '/') {
id = parts[0];
} else {
id = parts[1] || parts[0];
}
}
if (!$ref.refs[id]) {
$ref.refs[id] = ref;
}
}
}
(refs || []).concat([schema]).forEach(function(ref) {
schema = $.normalizeSchema(fakeroot, ref, push);
push(schema);
});
return $.resolveSchema(schema, $ref.refs, ex);
}
$ref.refs = {};
$ref.util = $;
return $ref;
};
instance.util = $;
},{"./util/find-reference":21,"./util/normalize-schema":22,"./util/resolve-schema":23,"./util/uri-helpers":24}],20:[function(require,module,exports){
'use strict';
var clone = module.exports = function(obj, seen) {
seen = seen || [];
if (seen.indexOf(obj) > -1) {
throw new Error('unable dereference circular structures');
}
if (!obj || typeof obj !== 'object') {
return obj;
}
seen = seen.concat([obj]);
var target = Array.isArray(obj) ? [] : {};
function copy(key, value) {
target[key] = clone(value, seen);
}
if (Array.isArray(target)) {
obj.forEach(function(value, key) {
copy(key, value);
});
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
Object.keys(obj).forEach(function(key) {
copy(key, obj[key]);
});
}
return target;
};
},{}],21:[function(require,module,exports){
'use strict';
var $ = require('./uri-helpers');
function get(obj, path) {
var hash = path.split('#')[1];
var parts = hash.split('/').slice(1);
while (parts.length) {
var key = decodeURIComponent(parts.shift()).replace(/~1/g, '/').replace(/~0/g, '~');
if (typeof obj[key] === 'undefined') {
throw new Error('JSON pointer not found: ' + path);
}
obj = obj[key];
}
return obj;
}
var find = module.exports = function(id, refs) {
var target = refs[id] || refs[id.split('#')[1]] || refs[$.getDocumentURI(id)];
if (target) {
target = id.indexOf('#/') > -1 ? get(target, id) : target;
} else {
for (var key in refs) {
if ($.resolveURL(refs[key].id, id) === refs[key].id) {
target = refs[key];
break;
}
}
}
if (!target) {
throw new Error('Reference not found: ' + id);
}
while (target.$ref) {
target = find(target.$ref, refs);
}
return target;
};
},{"./uri-helpers":24}],22:[function(require,module,exports){
'use strict';
var $ = require('./uri-helpers');
var cloneObj = require('./clone-obj');
var SCHEMA_URI = [
'http://json-schema.org/schema#',
'http://json-schema.org/draft-04/schema#'
];
function expand(obj, parent, callback) {
if (obj) {
var id = typeof obj.id === 'string' ? obj.id : '#';
if (!$.isURL(id)) {
id = $.resolveURL(parent === id ? null : parent, id);
}
if (typeof obj.$ref === 'string' && !$.isURL(obj.$ref)) {
obj.$ref = $.resolveURL(id, obj.$ref);
}
if (typeof obj.id === 'string') {
obj.id = parent = id;
}
}
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object' && !(key === 'enum' || key === 'required')) {
expand(value, parent, callback);
}
}
if (typeof callback === 'function') {
callback(obj);
}
}
module.exports = function(fakeroot, schema, push) {
if (typeof fakeroot === 'object') {
push = schema;
schema = fakeroot;
fakeroot = null;
}
var base = fakeroot || '',
copy = cloneObj(schema);
if (copy.$schema && SCHEMA_URI.indexOf(copy.$schema) === -1) {
throw new Error('Unsupported schema version (v4 only)');
}
base = $.resolveURL(copy.$schema || SCHEMA_URI[0], base);
expand(copy, $.resolveURL(copy.id || '#', base), push);
copy.id = copy.id || base;
return copy;
};
},{"./clone-obj":20,"./uri-helpers":24}],23:[function(require,module,exports){
'use strict';
var $ = require('./uri-helpers');
var find = require('./find-reference');
var deepExtend = require('deep-extend');
function isKey(prop) {
return prop === 'enum' || prop === 'required' || prop === 'definitions';
}
function copy(obj, refs, parent, resolve) {
var target = Array.isArray(obj) ? [] : {};
if (typeof obj.$ref === 'string') {
var base = $.getDocumentURI(obj.$ref);
if (parent !== base || (resolve && obj.$ref.indexOf('#/') > -1)) {
var fixed = find(obj.$ref, refs);
deepExtend(obj, fixed);
delete obj.$ref;
delete obj.id;
}
}
for (var prop in obj) {
if (typeof obj[prop] === 'object' && !isKey(prop)) {
target[prop] = copy(obj[prop], refs, parent, resolve);
} else {
target[prop] = obj[prop];
}
}
return target;
}
module.exports = function(obj, refs, resolve) {
var fixedId = $.resolveURL(obj.$schema, obj.id),
parent = $.getDocumentURI(fixedId);
return copy(obj, refs, parent, resolve);
};
},{"./find-reference":21,"./uri-helpers":24,"deep-extend":25}],24:[function(require,module,exports){
'use strict';
// https://gist.github.com/pjt33/efb2f1134bab986113fd
function URLUtils(url, baseURL) {
// remove leading ./
url = url.replace(/^\.\//, '');
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@]*)(?::([^:@]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
if (!m) {
throw new RangeError();
}
var href = m[0] || '';
var protocol = m[1] || '';
var username = m[2] || '';
var password = m[3] || '';
var host = m[4] || '';
var hostname = m[5] || '';
var port = m[6] || '';
var pathname = m[7] || '';
var search = m[8] || '';
var hash = m[9] || '';
if (baseURL !== undefined) {
var base = new URLUtils(baseURL);
var flag = protocol === '' && host === '' && username === '';
if (flag && pathname === '' && search === '') {
search = base.search;
}
if (flag && pathname.charAt(0) !== '/') {
pathname = (pathname !== '' ? (base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + pathname) : base.pathname);
}
// dot segments removal
var output = [];
pathname.replace(/\/?[^\/]+/g, function(p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
pathname = output.join('') || '/';
if (flag) {
port = base.port;
hostname = base.hostname;
host = base.host;
password = base.password;
username = base.username;
}
if (protocol === '') {
protocol = base.protocol;
}
href = protocol + (host !== '' ? '//' : '') + (username !== '' ? username + (password !== '' ? ':' + password : '') + '@' : '') + host + pathname + search + hash;
}
this.href = href;
this.origin = protocol + (host !== '' ? '//' + host : '');
this.protocol = protocol;
this.username = username;
this.password = password;
this.host = host;
this.hostname = hostname;
this.port = port;
this.pathname = pathname;
this.search = search;
this.hash = hash;
}
function isURL(path) {
if (typeof path === 'string' && /^\w+:\/\//.test(path)) {
return true;
}
}
function parseURI(href, base) {
return new URLUtils(href, base);
}
function resolveURL(base, href) {
base = base || 'http://json-schema.org/schema#';
href = parseURI(href, base);
base = parseURI(base);
if (base.hash && !href.hash) {
return href.href + base.hash;
}
return href.href;
}
function getDocumentURI(uri) {
return typeof uri === 'string' && uri.split('#')[0];
}
module.exports = {
isURL: isURL,
parseURI: parseURI,
resolveURL: resolveURL,
getDocumentURI: getDocumentURI
};
},{}],25:[function(require,module,exports){
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
function isSpecificValue(val) {
return (
val instanceof Buffer
|| val instanceof Date
|| val instanceof RegExp
) ? true : false;
}
function cloneSpecificValue(val) {
if (val instanceof Buffer) {
var x = new Buffer(val.length);
val.copy(x);
return x;
} else if (val instanceof Date) {
return new Date(val.getTime());
} else if (val instanceof RegExp) {
return new RegExp(val);
} else {
throw new Error('Unexpected situation');
}
}
/**
* Recursive cloning array.
*/
function deepCloneArray(arr) {
var clone = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
/**
* Extening object that entered in first argument.
*
* Returns extended object or false if have no target object or incorrect type.
*
* If you wish to clone source object (without modify it), just use empty new
* object as first argument, like this:
* deepExtend({}, yourObj_1, [yourObj_N]);
*/
var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) {
if (arguments.length < 1 || typeof arguments[0] !== 'object') {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
var target = arguments[0];
// convert arguments to array and cut off target object
var args = Array.prototype.slice.call(arguments, 1);
var val, src, clone;
args.forEach(function (obj) {
// skip argument if it is array or isn't object
if (typeof obj !== 'object' || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function (key) {
src = target[key]; // source value
val = obj[key]; // new value
// recursion prevention
if (val === target) {
return;
/**
* if new value isn't object then just overwrite by new value
* instead of extending.
*/
} else if (typeof val !== 'object' || val === null) {
target[key] = val;
return;
// just clone arrays (and recursive clone objects inside)
} else if (Array.isArray(val)) {
target[key] = deepCloneArray(val);
return;
// custom cloning and overwrite for specific objects
} else if (isSpecificValue(val)) {
target[key] = cloneSpecificValue(val);
return;
// overwrite by new value if source isn't object or array
} else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val);
return;
// source value and new value is objects both, extending...
} else {
target[key] = deepExtend(src, val);
return;
}
});
});
return target;
}
},{}],26:[function(require,module,exports){
function Address (faker) {
var f = faker.fake,
Helpers = faker.helpers;
this.zipCode = function(format) {
// if zip format is not specified, use the zip format defined for the locale
if (typeof format === 'undefined') {
var localeFormat = faker.definitions.address.postcode;
if (typeof localeFormat === 'string') {
format = localeFormat;
} else {
format = faker.random.arrayElement(localeFormat);
}
}
return Helpers.replaceSymbols(format);
}
this.city = function (format) {
var formats = [
'{{address.cityPrefix}} {{name.firstName}} {{address.citySuffix}}',
'{{address.cityPrefix}} {{name.firstName}}',
'{{name.firstName}} {{address.citySuffix}}',
'{{name.lastName}} {{address.citySuffix}}'
];
if (typeof format !== "number") {
format = faker.random.number(formats.length - 1);
}
return f(formats[format]);
}
this.cityPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.city_prefix);
}
this.citySuffix = function () {
return faker.random.arrayElement(faker.definitions.address.city_suffix);
}
this.streetName = function () {
var result;
var suffix = faker.address.streetSuffix();
if (suffix !== "") {
suffix = " " + suffix
}
switch (faker.random.number(1)) {
case 0:
result = faker.name.lastName() + suffix;
break;
case 1:
result = faker.name.firstName() + suffix;
break;
}
return result;
}
//
// TODO: change all these methods that accept a boolean to instead accept an options hash.
//
this.streetAddress = function (useFullAddress) {
if (useFullAddress === undefined) { useFullAddress = false; }
var address = "";
switch (faker.random.number(2)) {
case 0:
address = Helpers.replaceSymbolWithNumber("#####") + " " + faker.address.streetName();
break;
case 1:
address = Helpers.replaceSymbolWithNumber("####") + " " + faker.address.streetName();
break;
case 2:
address = Helpers.replaceSymbolWithNumber("###") + " " + faker.address.streetName();
break;
}
return useFullAddress ? (address + " " + faker.address.secondaryAddress()) : address;
}
this.streetSuffix = function () {
return faker.random.arrayElement(faker.definitions.address.street_suffix);
}
this.streetPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.street_prefix);
}
this.secondaryAddress = function () {
return Helpers.replaceSymbolWithNumber(faker.random.arrayElement(
[
'Apt. ###',
'Suite ###'
]
));
}
this.county = function () {
return faker.random.arrayElement(faker.definitions.address.county);
}
this.country = function () {
return faker.random.arrayElement(faker.definitions.address.country);
}
this.countryCode = function () {
return faker.random.arrayElement(faker.definitions.address.country_code);
}
this.state = function (useAbbr) {
return faker.random.arrayElement(faker.definitions.address.state);
}
this.stateAbbr = function () {
return faker.random.arrayElement(faker.definitions.address.state_abbr);
}
this.latitude = function () {
return (faker.random.number(180 * 10000) / 10000.0 - 90.0).toFixed(4);
}
this.longitude = function () {
return (faker.random.number(360 * 10000) / 10000.0 - 180.0).toFixed(4);
}
return this;
}
module.exports = Address;
},{}],27:[function(require,module,exports){
var Commerce = function (faker) {
var self = this;
self.color = function() {
return faker.random.arrayElement(faker.definitions.commerce.color);
};
self.department = function(max, fixedAmount) {
return faker.random.arrayElement(faker.definitions.commerce.department);
/*
max = max || 3;
var num = Math.floor((Math.random() * max) + 1);
if (fixedAmount) {
num = max;
}
var categories = faker.commerce.categories(num);
if(num > 1) {
return faker.commerce.mergeCategories(categories);
}
return categories[0];
*/
};
self.productName = function() {
return faker.commerce.productAdjective() + " " +
faker.commerce.productMaterial() + " " +
faker.commerce.product();
};
self.price = function(min, max, dec, symbol) {
min = min || 0;
max = max || 1000;
dec = dec || 2;
symbol = symbol || '';
if(min < 0 || max < 0) {
return symbol + 0.00;
}
return symbol + (Math.round((Math.random() * (max - min) + min) * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
};
/*
self.categories = function(num) {
var categories = [];
do {
var category = faker.random.arrayElement(faker.definitions.commerce.department);
if(categories.indexOf(category) === -1) {
categories.push(category);
}
} while(categories.length < num);
return categories;
};
*/
/*
self.mergeCategories = function(categories) {
var separator = faker.definitions.separator || " &";
// TODO: find undefined here
categories = categories || faker.definitions.commerce.categories;
var commaSeparated = categories.slice(0, -1).join(', ');
return [commaSeparated, categories[categories.length - 1]].join(separator + " ");
};
*/
self.productAdjective = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.adjective);
};
self.productMaterial = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.material);
};
self.product = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.product);
}
return self;
};
module['exports'] = Commerce;
},{}],28:[function(require,module,exports){
var Company = function (faker) {
var self = this;
var f = faker.fake;
this.suffixes = function () {
// Don't want the source array exposed to modification, so return a copy
return faker.definitions.company.suffix.slice(0);
}
this.companyName = function (format) {
var formats = [
'{{name.lastName}} {{company.companySuffix}}',
'{{name.lastName}} - {{name.lastName}}',
'{{name.lastName}}, {{name.lastName}} and {{name.lastName}}'
];
if (typeof format !== "number") {
format = faker.random.number(formats.length - 1);
}
return f(formats[format]);
}
this.companySuffix = function () {
return faker.random.arrayElement(faker.company.suffixes());
}
this.catchPhrase = function () {
return f('{{company.catchPhraseAdjective}} {{company.catchPhraseDescriptor}} {{company.catchPhraseNoun}}')
}
this.bs = function () {
return f('{{company.bsAdjective}} {{company.bsBuzz}} {{company.bsNoun}}');
}
this.catchPhraseAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.adjective);
}
this.catchPhraseDescriptor = function () {
return faker.random.arrayElement(faker.definitions.company.descriptor);
}
this.catchPhraseNoun = function () {
return faker.random.arrayElement(faker.definitions.company.noun);
}
this.bsAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.bs_adjective);
}
this.bsBuzz = function () {
return faker.random.arrayElement(faker.definitions.company.bs_verb);
}
this.bsNoun = function () {
return faker.random.arrayElement(faker.definitions.company.bs_noun);
}
}
module['exports'] = Company;
},{}],29:[function(require,module,exports){
var _Date = function (faker) {
var self = this;
self.past = function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var past = date.getTime();
past -= faker.random.number(range); // some time from now to N years ago, in milliseconds
date.setTime(past);
return date;
};
self.future = function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var future = date.getTime();
future += faker.random.number(range); // some time from now to N years later, in milliseconds
date.setTime(future);
return date;
};
self.between = function (from, to) {
var fromMilli = Date.parse(from);
var dateOffset = faker.random.number(Date.parse(to) - fromMilli);
var newDate = new Date(fromMilli + dateOffset);
return newDate;
};
self.recent = function (days) {
var date = new Date();
var range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000
};
var future = date.getTime();
future -= faker.random.number(range); // some time from now to N days ago, in milliseconds
date.setTime(future);
return date;
};
self.month = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.month[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.month[type];
return faker.random.arrayElement(source);
};
self.weekday = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.weekday[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.weekday[type];
return faker.random.arrayElement(source);
};
return self;
};
module['exports'] = _Date;
},{}],30:[function(require,module,exports){
/*
fake.js - generator method for combining faker methods based on string input
*/
function Fake (faker) {
this.fake = function fake (str) {
// setup default response as empty string
var res = '';
// if incoming str parameter is not provided, return error message
if (typeof str !== 'string' || str.length === 0) {
res = 'string parameter is required!';
return res;
}
// find first matching {{ and }}
var start = str.search('{{');
var end = str.search('}}');
// if no {{ and }} is found, we are done
if (start === -1 && end === -1) {
return str;
}
// console.log('attempting to parse', str);
// extract method name from between the {{ }} that we found
// for example: {{name.firstName}}
var method = str.substr(start + 2, end - start - 2);
method = method.replace('}}', '');
method = method.replace('{{', '');
// console.log('method', method)
// split the method into module and function
var parts = method.split('.');
if (typeof faker[parts[0]] === "undefined") {
throw new Error('Invalid module: ' + parts[0]);
}
if (typeof faker[parts[0]][parts[1]] === "undefined") {
throw new Error('Invalid method: ' + parts[0] + "." + parts[1]);
}
// assign the function from the module.function namespace
var fn = faker[parts[0]][parts[1]];
// replace the found tag with the returned fake value
res = str.replace('{{' + method + '}}', fn());
// return the response recursively until we are done finding all tags
return fake(res);
}
return this;
}
module['exports'] = Fake;
},{}],31:[function(require,module,exports){
var Finance = function (faker) {
var Helpers = faker.helpers,
self = this;
self.account = function (length) {
length = length || 8;
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
length = null;
return Helpers.replaceSymbolWithNumber(template);
}
self.accountName = function () {
return [Helpers.randomize(faker.definitions.finance.account_type), 'Account'].join(' ');
}
self.mask = function (length, parens, elipsis) {
//set defaults
length = (length == 0 || !length || typeof length == 'undefined') ? 4 : length;
parens = (parens === null) ? true : parens;
elipsis = (elipsis === null) ? true : elipsis;
//create a template for length
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
//prefix with elipsis
template = (elipsis) ? ['...', template].join('') : template;
template = (parens) ? ['(', template, ')'].join('') : template;
//generate random numbers
template = Helpers.replaceSymbolWithNumber(template);
return template;
}
//min and max take in minimum and maximum amounts, dec is the decimal place you want rounded to, symbol is $, €, £, etc
//NOTE: this returns a string representation of the value, if you want a number use parseFloat and no symbol
self.amount = function (min, max, dec, symbol) {
min = min || 0;
max = max || 1000;
dec = dec || 2;
symbol = symbol || '';
return symbol + (Math.round((Math.random() * (max - min) + min) * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
}
self.transactionType = function () {
return Helpers.randomize(faker.definitions.finance.transaction_type);
}
self.currencyCode = function () {
return faker.random.objectElement(faker.definitions.finance.currency)['code'];
}
self.currencyName = function () {
return faker.random.objectElement(faker.definitions.finance.currency, 'key');
}
self.currencySymbol = function () {
var symbol;
while (!symbol) {
symbol = faker.random.objectElement(faker.definitions.finance.currency)['symbol'];
}
return symbol;
}
}
module['exports'] = Finance;
},{}],32:[function(require,module,exports){
var Hacker = function (faker) {
var self = this;
self.abbreviation = function () {
return faker.random.arrayElement(faker.definitions.hacker.abbreviation);
};
self.adjective = function () {
return faker.random.arrayElement(faker.definitions.hacker.adjective);
};
self.noun = function () {
return faker.random.arrayElement(faker.definitions.hacker.noun);
};
self.verb = function () {
return faker.random.arrayElement(faker.definitions.hacker.verb);
};
self.ingverb = function () {
return faker.random.arrayElement(faker.definitions.hacker.ingverb);
};
self.phrase = function () {
var data = {
abbreviation: self.abbreviation(),
adjective: self.adjective(),
ingverb: self.ingverb(),
noun: self.noun(),
verb: self.verb()
};
var phrase = faker.random.arrayElement([ "If we {{verb}} the {{noun}}, we can get to the {{abbreviation}} {{noun}} through the {{adjective}} {{abbreviation}} {{noun}}!",
"We need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"Try to {{verb}} the {{abbreviation}} {{noun}}, maybe it will {{verb}} the {{adjective}} {{noun}}!",
"You can't {{verb}} the {{noun}} without {{ingverb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"Use the {{adjective}} {{abbreviation}} {{noun}}, then you can {{verb}} the {{adjective}} {{noun}}!",
"The {{abbreviation}} {{noun}} is down, {{verb}} the {{adjective}} {{noun}} so we can {{verb}} the {{abbreviation}} {{noun}}!",
"{{ingverb}} the {{noun}} won't do anything, we need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"I'll {{verb}} the {{adjective}} {{abbreviation}} {{noun}}, that should {{noun}} the {{abbreviation}} {{noun}}!"
]);
return faker.helpers.mustache(phrase, data);
};
return self;
};
module['exports'] = Hacker;
},{}],33:[function(require,module,exports){
var Helpers = function (faker) {
var self = this;
// backword-compatibility
self.randomize = function (array) {
array = array || ["a", "b", "c"];
return faker.random.arrayElement(array);
};
// slugifies string
self.slugify = function (string) {
string = string || "";
return string.replace(/ /g, '-').replace(/[^\w\.\-]+/g, '');
};
// parses string for a symbol and replace it with a random number from 1-10
self.replaceSymbolWithNumber = function (string, symbol) {
string = string || "";
// default symbol is '#'
if (symbol === undefined) {
symbol = '#';
}
var str = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == symbol) {
str += faker.random.number(9);
} else {
str += string.charAt(i);
}
}
return str;
};
// parses string for symbols (numbers or letters) and replaces them appropriately
self.replaceSymbols = function (string) {
string = string || "";
var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
var str = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == "#") {
str += faker.random.number(9);
} else if (string.charAt(i) == "?") {
str += alpha[Math.floor(Math.random() * alpha.length)];
} else {
str += string.charAt(i);
}
}
return str;
};
// takes an array and returns it randomized
self.shuffle = function (o) {
o = o || ["a", "b", "c"];
for (var j, x, i = o.length-1; i; j = faker.random.number(i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
self.mustache = function (str, data) {
if (typeof str === 'undefined') {
return '';
}
for(var p in data) {
var re = new RegExp('{{' + p + '}}', 'g')
str = str.replace(re, data[p]);
}
return str;
};
self.createCard = function () {
return {
"name": faker.name.findName(),
"username": faker.internet.userName(),
"email": faker.internet.email(),
"address": {
"streetA": faker.address.streetName(),
"streetB": faker.address.streetAddress(),
"streetC": faker.address.streetAddress(true),
"streetD": faker.address.secondaryAddress(),
"city": faker.address.city(),
"state": faker.address.state(),
"country": faker.address.country(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"phone": faker.phone.phoneNumber(),
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
},
"posts": [
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
},
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
},
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
}
],
"accountHistory": [faker.helpers.createTransaction(), faker.helpers.createTransaction(), faker.helpers.createTransaction()]
};
};
self.contextualCard = function () {
var name = faker.name.firstName(),
userName = faker.internet.userName(name);
return {
"name": name,
"username": userName,
"avatar": faker.internet.avatar(),
"email": faker.internet.email(userName),
"dob": faker.date.past(50, new Date("Sat Sep 20 1992 21:35:02 GMT+0200 (CEST)")),
"phone": faker.phone.phoneNumber(),
"address": {
"street": faker.address.streetName(true),
"suite": faker.address.secondaryAddress(),
"city": faker.address.city(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
}
};
};
self.userCard = function () {
return {
"name": faker.name.findName(),
"username": faker.internet.userName(),
"email": faker.internet.email(),
"address": {
"street": faker.address.streetName(true),
"suite": faker.address.secondaryAddress(),
"city": faker.address.city(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"phone": faker.phone.phoneNumber(),
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
}
};
};
self.createTransaction = function(){
return {
"amount" : faker.finance.amount(),
"date" : new Date(2012, 1, 2), //TODO: add a ranged date method
"business": faker.company.companyName(),
"name": [faker.finance.accountName(), faker.finance.mask()].join(' '),
"type" : self.randomize(faker.definitions.finance.transaction_type),
"account" : faker.finance.account()
};
};
return self;
};
/*
String.prototype.capitalize = function () { //v1.0
return this.replace(/\w+/g, function (a) {
return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
});
};
*/
module['exports'] = Helpers;
},{}],34:[function(require,module,exports){
var Image = function (faker) {
var self = this;
self.image = function () {
var categories = ["abstract", "animals", "business", "cats", "city", "food", "nightlife", "fashion", "people", "nature", "sports", "technics", "transport"];
return self[faker.random.arrayElement(categories)]();
};
self.avatar = function () {
return faker.internet.avatar();
};
self.imageUrl = function (width, height, category) {
var width = width || 640;
var height = height || 480;
var url ='http://lorempixel.com/' + width + '/' + height;
if (typeof category !== 'undefined') {
url += '/' + category;
}
return url;
};
self.abstract = function (width, height) {
return faker.image.imageUrl(width, height, 'abstract');
};
self.animals = function (width, height) {
return faker.image.imageUrl(width, height, 'animals');
};
self.business = function (width, height) {
return faker.image.imageUrl(width, height, 'business');
};
self.cats = function (width, height) {
return faker.image.imageUrl(width, height, 'cats');
};
self.city = function (width, height) {
return faker.image.imageUrl(width, height, 'city');
};
self.food = function (width, height) {
return faker.image.imageUrl(width, height, 'food');
};
self.nightlife = function (width, height) {
return faker.image.imageUrl(width, height, 'nightlife');
};
self.fashion = function (width, height) {
return faker.image.imageUrl(width, height, 'fashion');
};
self.people = function (width, height) {
return faker.image.imageUrl(width, height, 'people');
};
self.nature = function (width, height) {
return faker.image.imageUrl(width, height, 'nature');
};
self.sports = function (width, height) {
return faker.image.imageUrl(width, height, 'sports');
};
self.technics = function (width, height) {
return faker.image.imageUrl(width, height, 'technics');
};
self.transport = function (width, height) {
return faker.image.imageUrl(width, height, 'transport');
}
}
module["exports"] = Image;
},{}],35:[function(require,module,exports){
/*
this index.js file is used for including the faker library as a CommonJS module, instead of a bundle
you can include the faker library into your existing node.js application by requiring the entire /faker directory
var faker = require(./faker);
var randomName = faker.name.findName();
you can also simply include the "faker.js" file which is the auto-generated bundled version of the faker library
var faker = require(./customAppPath/faker);
var randomName = faker.name.findName();
if you plan on modifying the faker library you should be performing your changes in the /lib/ directory
*/
function Faker (opts) {
var self = this;
opts = opts || {};
// assign options
var locales = self.locales || opts.locales || {};
var locale = self.locale || opts.locale || "en";
var localeFallback = self.localeFallback || opts.localeFallback || "en";
self.locales = locales;
self.locale = locale;
self.localeFallback = localeFallback;
self.definitions = {};
var Fake = require('./fake');
self.fake = new Fake(self).fake;
var Random = require('./random');
self.random = new Random(self);
// self.random = require('./random');
var Helpers = require('./helpers');
self.helpers = new Helpers(self);
var Name = require('./name');
self.name = new Name(self);
// self.name = require('./name');
var Address = require('./address');
self.address = new Address(self);
var Company = require('./company');
self.company = new Company(self);
var Finance = require('./finance');
self.finance = new Finance(self);
var Image = require('./image');
self.image = new Image(self);
var Lorem = require('./lorem');
self.lorem = new Lorem(self);
var Hacker = require('./hacker');
self.hacker = new Hacker(self);
var Internet = require('./internet');
self.internet = new Internet(self);
var Phone = require('./phone_number');
self.phone = new Phone(self);
var _Date = require('./date');
self.date = new _Date(self);
var Commerce = require('./commerce');
self.commerce = new Commerce(self);
// TODO: fix self.commerce = require('./commerce');
var _definitions = {
"name": ["first_name", "last_name", "prefix", "suffix", "title", "male_first_name", "female_first_name", "male_middle_name", "female_middle_name", "male_last_name", "female_last_name"],
"address": ["city_prefix", "city_suffix", "street_suffix", "county", "country", "country_code", "state", "state_abbr", "street_prefix", "postcode"],
"company": ["adjective", "noun", "descriptor", "bs_adjective", "bs_noun", "bs_verb", "suffix"],
"lorem": ["words"],
"hacker": ["abbreviation", "adjective", "noun", "verb", "ingverb"],
"phone_number": ["formats"],
"finance": ["account_type", "transaction_type", "currency"],
"internet": ["avatar_uri", "domain_suffix", "free_email", "password"],
"commerce": ["color", "department", "product_name", "price", "categories"],
"date": ["month", "weekday"],
"title": "",
"separator": ""
};
// Create a Getter for all definitions.foo.bar propetries
Object.keys(_definitions).forEach(function(d){
if (typeof self.definitions[d] === "undefined") {
self.definitions[d] = {};
}
if (typeof _definitions[d] === "string") {
self.definitions[d] = _definitions[d];
return;
}
_definitions[d].forEach(function(p){
Object.defineProperty(self.definitions[d], p, {
get: function () {
if (typeof self.locales[self.locale][d] === "undefined" || typeof self.locales[self.locale][d][p] === "undefined") {
// certain localization sets contain less data then others.
// in the case of a missing defintion, use the default localeFallback to substitute the missing set data
// throw new Error('unknown property ' + d + p)
return self.locales[localeFallback][d][p];
} else {
// return localized data
return self.locales[self.locale][d][p];
}
}
});
});
});
};
Faker.prototype.seed = function(value) {
var Random = require('./random');
this.seedValue = value;
this.random = new Random(this, this.seedValue);
}
module['exports'] = Faker;
},{"./address":26,"./commerce":27,"./company":28,"./date":29,"./fake":30,"./finance":31,"./hacker":32,"./helpers":33,"./image":34,"./internet":36,"./lorem":161,"./name":162,"./phone_number":163,"./random":164}],36:[function(require,module,exports){
var password_generator = require('../vendor/password-generator.js'),
random_ua = require('../vendor/user-agent');
var Internet = function (faker) {
var self = this;
self.avatar = function () {
return faker.random.arrayElement(faker.definitions.internet.avatar_uri);
};
self.email = function (firstName, lastName, provider) {
provider = provider || faker.random.arrayElement(faker.definitions.internet.free_email);
return faker.helpers.slugify(faker.internet.userName(firstName, lastName)) + "@" + provider;
};
self.userName = function (firstName, lastName) {
var result;
firstName = firstName || faker.name.firstName();
lastName = lastName || faker.name.lastName();
switch (faker.random.number(2)) {
case 0:
result = firstName + faker.random.number(99);
break;
case 1:
result = firstName + faker.random.arrayElement([".", "_"]) + lastName;
break;
case 2:
result = firstName + faker.random.arrayElement([".", "_"]) + lastName + faker.random.number(99);
break;
}
result = result.toString().replace(/'/g, "");
result = result.replace(/ /g, "");
return result;
};
self.protocol = function () {
var protocols = ['http','https'];
return faker.random.arrayElement(protocols);
};
self.url = function () {
return faker.internet.protocol() + '://' + faker.internet.domainName();
};
self.domainName = function () {
return faker.internet.domainWord() + "." + faker.internet.domainSuffix();
};
self.domainSuffix = function () {
return faker.random.arrayElement(faker.definitions.internet.domain_suffix);
};
self.domainWord = function () {
return faker.name.firstName().replace(/([\\~#&*{}/:<>?|\"])/ig, '').toLowerCase();
};
self.ip = function () {
var randNum = function () {
return (faker.random.number(255)).toFixed(0);
};
var result = [];
for (var i = 0; i < 4; i++) {
result[i] = randNum();
}
return result.join(".");
};
self.userAgent = function () {
return random_ua.generate();
};
self.color = function (baseRed255, baseGreen255, baseBlue255) {
baseRed255 = baseRed255 || 0;
baseGreen255 = baseGreen255 || 0;
baseBlue255 = baseBlue255 || 0;
// based on awesome response : http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette
var red = Math.floor((faker.random.number(256) + baseRed255) / 2);
var green = Math.floor((faker.random.number(256) + baseGreen255) / 2);
var blue = Math.floor((faker.random.number(256) + baseBlue255) / 2);
var redStr = red.toString(16);
var greenStr = green.toString(16);
var blueStr = blue.toString(16);
return '#' +
(redStr.length === 1 ? '0' : '') + redStr +
(greenStr.length === 1 ? '0' : '') + greenStr +
(blueStr.length === 1 ? '0': '') + blueStr;
};
self.mac = function(){
var i, mac = "";
for (i=0; i < 12; i++) {
mac+= parseInt(Math.random()*16).toString(16);
if (i%2==1 && i != 11) {
mac+=":";
}
}
return mac;
};
self.password = function (len, memorable, pattern, prefix) {
len = len || 15;
if (typeof memorable === "undefined") {
memorable = false;
}
return password_generator(len, memorable, pattern, prefix);
}
};
module["exports"] = Internet;
},{"../vendor/password-generator.js":167,"../vendor/user-agent":168}],37:[function(require,module,exports){
module["exports"] = [
"#####",
"####",
"###"
];
},{}],38:[function(require,module,exports){
module["exports"] = [
"#{city_prefix} #{Name.first_name}#{city_suffix}",
"#{city_prefix} #{Name.first_name}",
"#{Name.first_name}#{city_suffix}",
"#{Name.last_name}#{city_suffix}"
];
},{}],39:[function(require,module,exports){
module["exports"] = [
"North",
"East",
"West",
"South",
"New",
"Lake",
"Port"
];
},{}],40:[function(require,module,exports){
module["exports"] = [
"town",
"ton",
"land",
"ville",
"berg",
"burgh",
"borough",
"bury",
"view",
"port",
"mouth",
"stad",
"furt",
"chester",
"mouth",
"fort",
"haven",
"side",
"shire"
];
},{}],41:[function(require,module,exports){
module["exports"] = [
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica (the territory South of 60 deg S)",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island (Bouvetoya)",
"Brazil",
"British Indian Ocean Territory (Chagos Archipelago)",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",
"Canada",
"Cape Verde",
"Cayman Islands",
"Central African Republic",
"Chad",
"Chile",
"China",
"Christmas Island",
"Cocos (Keeling) Islands",
"Colombia",
"Comoros",
"Congo",
"Congo",
"Cook Islands",
"Costa Rica",
"Cote d'Ivoire",
"Croatia",
"Cuba",
"Cyprus",
"Czech Republic",
"Denmark",
"Djibouti",
"Dominica",
"Dominican Republic",
"Ecuador",
"Egypt",
"El Salvador",
"Equatorial Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Faroe Islands",
"Falkland Islands (Malvinas)",
"Fiji",
"Finland",
"France",
"French Guiana",
"French Polynesia",
"French Southern Territories",
"Gabon",
"Gambia",
"Georgia",
"Germany",
"Ghana",
"Gibraltar",
"Greece",
"Greenland",
"Grenada",
"Guadeloupe",
"Guam",
"Guatemala",
"Guernsey",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Heard Island and McDonald Islands",
"Holy See (Vatican City State)",
"Honduras",
"Hong Kong",
"Hungary",
"Iceland",
"India",
"Indonesia",
"Iran",
"Iraq",
"Ireland",
"Isle of Man",
"Israel",
"Italy",
"Jamaica",
"Japan",
"Jersey",
"Jordan",
"Kazakhstan",
"Kenya",
"Kiribati",
"Democratic People's Republic of Korea",
"Republic of Korea",
"Kuwait",
"Kyrgyz Republic",
"Lao People's Democratic Republic",
"Latvia",
"Lebanon",
"Lesotho",
"Liberia",
"Libyan Arab Jamahiriya",
"Liechtenstein",
"Lithuania",
"Luxembourg",
"Macao",
"Macedonia",
"Madagascar",
"Malawi",
"Malaysia",
"Maldives",
"Mali",
"Malta",
"Marshall Islands",
"Martinique",
"Mauritania",
"Mauritius",
"Mayotte",
"Mexico",
"Micronesia",
"Moldova",
"Monaco",
"Mongolia",
"Montenegro",
"Montserrat",
"Morocco",
"Mozambique",
"Myanmar",
"Namibia",
"Nauru",
"Nepal",
"Netherlands Antilles",
"Netherlands",
"New Caledonia",
"New Zealand",
"Nicaragua",
"Niger",
"Nigeria",
"Niue",
"Norfolk Island",
"Northern Mariana Islands",
"Norway",
"Oman",
"Pakistan",
"Palau",
"Palestinian Territory",
"Panama",
"Papua New Guinea",
"Paraguay",
"Peru",
"Philippines",
"Pitcairn Islands",
"Poland",
"Portugal",
"Puerto Rico",
"Qatar",
"Reunion",
"Romania",
"Russian Federation",
"Rwanda",
"Saint Barthelemy",
"Saint Helena",
"Saint Kitts and Nevis",
"Saint Lucia",
"Saint Martin",
"Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines",
"Samoa",
"San Marino",
"Sao Tome and Principe",
"Saudi Arabia",
"Senegal",
"Serbia",
"Seychelles",
"Sierra Leone",
"Singapore",
"Slovakia (Slovak Republic)",
"Slovenia",
"Solomon Islands",
"Somalia",
"South Africa",
"South Georgia and the South Sandwich Islands",
"Spain",
"Sri Lanka",
"Sudan",
"Suriname",
"Svalbard & Jan Mayen Islands",
"Swaziland",
"Sweden",
"Switzerland",
"Syrian Arab Republic",
"Taiwan",
"Tajikistan",
"Tanzania",
"Thailand",
"Timor-Leste",
"Togo",
"Tokelau",
"Tonga",
"Trinidad and Tobago",
"Tunisia",
"Turkey",
"Turkmenistan",
"Turks and Caicos Islands",
"Tuvalu",
"Uganda",
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"United States of America",
"United States Minor Outlying Islands",
"Uruguay",
"Uzbekistan",
"Vanuatu",
"Venezuela",
"Vietnam",
"Virgin Islands, British",
"Virgin Islands, U.S.",
"Wallis and Futuna",
"Western Sahara",
"Yemen",
"Zambia",
"Zimbabwe"
];
},{}],42:[function(require,module,exports){
module["exports"] = [
"AD",
"AE",
"AF",
"AG",
"AI",
"AL",
"AM",
"AO",
"AQ",
"AR",
"AS",
"AT",
"AU",
"AW",
"AX",
"AZ",
"BA",
"BB",
"BD",
"BE",
"BF",
"BG",
"BH",
"BI",
"BJ",
"BL",
"BM",
"BN",
"BO",
"BQ",
"BQ",
"BR",
"BS",
"BT",
"BV",
"BW",
"BY",
"BZ",
"CA",
"CC",
"CD",
"CF",
"CG",
"CH",
"CI",
"CK",
"CL",
"CM",
"CN",
"CO",
"CR",
"CU",
"CV",
"CW",
"CX",
"CY",
"CZ",
"DE",
"DJ",
"DK",
"DM",
"DO",
"DZ",
"EC",
"EE",
"EG",
"EH",
"ER",
"ES",
"ET",
"FI",
"FJ",
"FK",
"FM",
"FO",
"FR",
"GA",
"GB",
"GD",
"GE",
"GF",
"GG",
"GH",
"GI",
"GL",
"GM",
"GN",
"GP",
"GQ",
"GR",
"GS",
"GT",
"GU",
"GW",
"GY",
"HK",
"HM",
"HN",
"HR",
"HT",
"HU",
"ID",
"IE",
"IL",
"IM",
"IN",
"IO",
"IQ",
"IR",
"IS",
"IT",
"JE",
"JM",
"JO",
"JP",
"KE",
"KG",
"KH",
"KI",
"KM",
"KN",
"KP",
"KR",
"KW",
"KY",
"KZ",
"LA",
"LB",
"LC",
"LI",
"LK",
"LR",
"LS",
"LT",
"LU",
"LV",
"LY",
"MA",
"MC",
"MD",
"ME",
"MF",
"MG",
"MH",
"MK",
"ML",
"MM",
"MN",
"MO",
"MP",
"MQ",
"MR",
"MS",
"MT",
"MU",
"MV",
"MW",
"MX",
"MY",
"MZ",
"NA",
"NC",
"NE",
"NF",
"NG",
"NI",
"NL",
"NO",
"NP",
"NR",
"NU",
"NZ",
"OM",
"PA",
"PE",
"PF",
"PG",
"PH",
"PK",
"PL",
"PM",
"PN",
"PR",
"PS",
"PT",
"PW",
"PY",
"QA",
"RE",
"RO",
"RS",
"RU",
"RW",
"SA",
"SB",
"SC",
"SD",
"SE",
"SG",
"SH",
"SI",
"SJ",
"SK",
"SL",
"SM",
"SN",
"SO",
"SR",
"SS",
"ST",
"SV",
"SX",
"SY",
"SZ",
"TC",
"TD",
"TF",
"TG",
"TH",
"TJ",
"TK",
"TL",
"TM",
"TN",
"TO",
"TR",
"TT",
"TV",
"TW",
"TZ",
"UA",
"UG",
"UM",
"US",
"UY",
"UZ",
"VA",
"VC",
"VE",
"VG",
"VI",
"VN",
"VU",
"WF",
"WS",
"YE",
"YT",
"ZA",
"ZM",
"ZW"
];
},{}],43:[function(require,module,exports){
module["exports"] = [
"Avon",
"Bedfordshire",
"Berkshire",
"Borders",
"Buckinghamshire",
"Cambridgeshire"
];
},{}],44:[function(require,module,exports){
module["exports"] = [
"United States of America"
];
},{}],45:[function(require,module,exports){
var address = {};
module['exports'] = address;
address.city_prefix = require("./city_prefix");
address.city_suffix = require("./city_suffix");
address.county = require("./county");
address.country = require("./country");
address.country_code = require("./country_code");
address.building_number = require("./building_number");
address.street_suffix = require("./street_suffix");
address.secondary_address = require("./secondary_address");
address.postcode = require("./postcode");
address.postcode_by_state = require("./postcode_by_state");
address.state = require("./state");
address.state_abbr = require("./state_abbr");
address.time_zone = require("./time_zone");
address.city = require("./city");
address.street_name = require("./street_name");
address.street_address = require("./street_address");
address.default_country = require("./default_country");
},{"./building_number":37,"./city":38,"./city_prefix":39,"./city_suffix":40,"./country":41,"./country_code":42,"./county":43,"./default_country":44,"./postcode":46,"./postcode_by_state":47,"./secondary_address":48,"./state":49,"./state_abbr":50,"./street_address":51,"./street_name":52,"./street_suffix":53,"./time_zone":54}],46:[function(require,module,exports){
module["exports"] = [
"#####",
"#####-####"
];
},{}],47:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"dup":46}],48:[function(require,module,exports){
module["exports"] = [
"Apt. ###",
"Suite ###"
];
},{}],49:[function(require,module,exports){
module["exports"] = [
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming"
];
},{}],50:[function(require,module,exports){
module["exports"] = [
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY"
];
},{}],51:[function(require,module,exports){
module["exports"] = [
"#{building_number} #{street_name}"
];
},{}],52:[function(require,module,exports){
module["exports"] = [
"#{Name.first_name} #{street_suffix}",
"#{Name.last_name} #{street_suffix}"
];
},{}],53:[function(require,module,exports){
module["exports"] = [
"Alley",
"Avenue",
"Branch",
"Bridge",
"Brook",
"Brooks",
"Burg",
"Burgs",
"Bypass",
"Camp",
"Canyon",
"Cape",
"Causeway",
"Center",
"Centers",
"Circle",
"Circles",
"Cliff",
"Cliffs",
"Club",
"Common",
"Corner",
"Corners",
"Course",
"Court",
"Courts",
"Cove",
"Coves",
"Creek",
"Crescent",
"Crest",
"Crossing",
"Crossroad",
"Curve",
"Dale",
"Dam",
"Divide",
"Drive",
"Drive",
"Drives",
"Estate",
"Estates",
"Expressway",
"Extension",
"Extensions",
"Fall",
"Falls",
"Ferry",
"Field",
"Fields",
"Flat",
"Flats",
"Ford",
"Fords",
"Forest",
"Forge",
"Forges",
"Fork",
"Forks",
"Fort",
"Freeway",
"Garden",
"Gardens",
"Gateway",
"Glen",
"Glens",
"Green",
"Greens",
"Grove",
"Groves",
"Harbor",
"Harbors",
"Haven",
"Heights",
"Highway",
"Hill",
"Hills",
"Hollow",
"Inlet",
"Inlet",
"Island",
"Island",
"Islands",
"Islands",
"Isle",
"Isle",
"Junction",
"Junctions",
"Key",
"Keys",
"Knoll",
"Knolls",
"Lake",
"Lakes",
"Land",
"Landing",
"Lane",
"Light",
"Lights",
"Loaf",
"Lock",
"Locks",
"Locks",
"Lodge",
"Lodge",
"Loop",
"Mall",
"Manor",
"Manors",
"Meadow",
"Meadows",
"Mews",
"Mill",
"Mills",
"Mission",
"Mission",
"Motorway",
"Mount",
"Mountain",
"Mountain",
"Mountains",
"Mountains",
"Neck",
"Orchard",
"Oval",
"Overpass",
"Park",
"Parks",
"Parkway",
"Parkways",
"Pass",
"Passage",
"Path",
"Pike",
"Pine",
"Pines",
"Place",
"Plain",
"Plains",
"Plains",
"Plaza",
"Plaza",
"Point",
"Points",
"Port",
"Port",
"Ports",
"Ports",
"Prairie",
"Prairie",
"Radial",
"Ramp",
"Ranch",
"Rapid",
"Rapids",
"Rest",
"Ridge",
"Ridges",
"River",
"Road",
"Road",
"Roads",
"Roads",
"Route",
"Row",
"Rue",
"Run",
"Shoal",
"Shoals",
"Shore",
"Shores",
"Skyway",
"Spring",
"Springs",
"Springs",
"Spur",
"Spurs",
"Square",
"Square",
"Squares",
"Squares",
"Station",
"Station",
"Stravenue",
"Stravenue",
"Stream",
"Stream",
"Street",
"Street",
"Streets",
"Summit",
"Summit",
"Terrace",
"Throughway",
"Trace",
"Track",
"Trafficway",
"Trail",
"Trail",
"Tunnel",
"Tunnel",
"Turnpike",
"Turnpike",
"Underpass",
"Union",
"Unions",
"Valley",
"Valleys",
"Via",
"Viaduct",
"View",
"Views",
"Village",
"Village",
"Villages",
"Ville",
"Vista",
"Vista",
"Walk",
"Walks",
"Wall",
"Way",
"Ways",
"Well",
"Wells"
];
},{}],54:[function(require,module,exports){
module["exports"] = [
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Honolulu",
"America/Juneau",
"America/Los_Angeles",
"America/Tijuana",
"America/Denver",
"America/Phoenix",
"America/Chihuahua",
"America/Mazatlan",
"America/Chicago",
"America/Regina",
"America/Mexico_City",
"America/Mexico_City",
"America/Monterrey",
"America/Guatemala",
"America/New_York",
"America/Indiana/Indianapolis",
"America/Bogota",
"America/Lima",
"America/Lima",
"America/Halifax",
"America/Caracas",
"America/La_Paz",
"America/Santiago",
"America/St_Johns",
"America/Sao_Paulo",
"America/Argentina/Buenos_Aires",
"America/Guyana",
"America/Godthab",
"Atlantic/South_Georgia",
"Atlantic/Azores",
"Atlantic/Cape_Verde",
"Europe/Dublin",
"Europe/London",
"Europe/Lisbon",
"Europe/London",
"Africa/Casablanca",
"Africa/Monrovia",
"Etc/UTC",
"Europe/Belgrade",
"Europe/Bratislava",
"Europe/Budapest",
"Europe/Ljubljana",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Skopje",
"Europe/Warsaw",
"Europe/Zagreb",
"Europe/Brussels",
"Europe/Copenhagen",
"Europe/Madrid",
"Europe/Paris",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Berlin",
"Europe/Rome",
"Europe/Stockholm",
"Europe/Vienna",
"Africa/Algiers",
"Europe/Bucharest",
"Africa/Cairo",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Riga",
"Europe/Sofia",
"Europe/Tallinn",
"Europe/Vilnius",
"Europe/Athens",
"Europe/Istanbul",
"Europe/Minsk",
"Asia/Jerusalem",
"Africa/Harare",
"Africa/Johannesburg",
"Europe/Moscow",
"Europe/Moscow",
"Europe/Moscow",
"Asia/Kuwait",
"Asia/Riyadh",
"Africa/Nairobi",
"Asia/Baghdad",
"Asia/Tehran",
"Asia/Muscat",
"Asia/Muscat",
"Asia/Baku",
"Asia/Tbilisi",
"Asia/Yerevan",
"Asia/Kabul",
"Asia/Yekaterinburg",
"Asia/Karachi",
"Asia/Karachi",
"Asia/Tashkent",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kathmandu",
"Asia/Dhaka",
"Asia/Dhaka",
"Asia/Colombo",
"Asia/Almaty",
"Asia/Novosibirsk",
"Asia/Rangoon",
"Asia/Bangkok",
"Asia/Bangkok",
"Asia/Jakarta",
"Asia/Krasnoyarsk",
"Asia/Shanghai",
"Asia/Chongqing",
"Asia/Hong_Kong",
"Asia/Urumqi",
"Asia/Kuala_Lumpur",
"Asia/Singapore",
"Asia/Taipei",
"Australia/Perth",
"Asia/Irkutsk",
"Asia/Ulaanbaatar",
"Asia/Seoul",
"Asia/Tokyo",
"Asia/Tokyo",
"Asia/Tokyo",
"Asia/Yakutsk",
"Australia/Darwin",
"Australia/Adelaide",
"Australia/Melbourne",
"Australia/Melbourne",
"Australia/Sydney",
"Australia/Brisbane",
"Australia/Hobart",
"Asia/Vladivostok",
"Pacific/Guam",
"Pacific/Port_Moresby",
"Asia/Magadan",
"Asia/Magadan",
"Pacific/Noumea",
"Pacific/Fiji",
"Asia/Kamchatka",
"Pacific/Majuro",
"Pacific/Auckland",
"Pacific/Auckland",
"Pacific/Tongatapu",
"Pacific/Fakaofo",
"Pacific/Apia"
];
},{}],55:[function(require,module,exports){
module["exports"] = [
"#{Name.name}",
"#{Company.name}"
];
},{}],56:[function(require,module,exports){
var app = {};
module['exports'] = app;
app.name = require("./name");
app.version = require("./version");
app.author = require("./author");
},{"./author":55,"./name":57,"./version":58}],57:[function(require,module,exports){
module["exports"] = [
"Redhold",
"Treeflex",
"Trippledex",
"Kanlam",
"Bigtax",
"Daltfresh",
"Toughjoyfax",
"Mat Lam Tam",
"Otcom",
"Tres-Zap",
"Y-Solowarm",
"Tresom",
"Voltsillam",
"Biodex",
"Greenlam",
"Viva",
"Matsoft",
"Temp",
"Zoolab",
"Subin",
"Rank",
"Job",
"Stringtough",
"Tin",
"It",
"Home Ing",
"Zamit",
"Sonsing",
"Konklab",
"Alpha",
"Latlux",
"Voyatouch",
"Alphazap",
"Holdlamis",
"Zaam-Dox",
"Sub-Ex",
"Quo Lux",
"Bamity",
"Ventosanzap",
"Lotstring",
"Hatity",
"Tempsoft",
"Overhold",
"Fixflex",
"Konklux",
"Zontrax",
"Tampflex",
"Span",
"Namfix",
"Transcof",
"Stim",
"Fix San",
"Sonair",
"Stronghold",
"Fintone",
"Y-find",
"Opela",
"Lotlux",
"Ronstring",
"Zathin",
"Duobam",
"Keylex"
];
},{}],58:[function(require,module,exports){
module["exports"] = [
"0.#.#",
"0.##",
"#.##",
"#.#",
"#.#.#"
];
},{}],59:[function(require,module,exports){
module["exports"] = [
"2011-10-12",
"2012-11-12",
"2015-11-11",
"2013-9-12"
];
},{}],60:[function(require,module,exports){
module["exports"] = [
"1234-2121-1221-1211",
"1212-1221-1121-1234",
"1211-1221-1234-2201",
"1228-1221-1221-1431"
];
},{}],61:[function(require,module,exports){
module["exports"] = [
"visa",
"mastercard",
"americanexpress",
"discover"
];
},{}],62:[function(require,module,exports){
var business = {};
module['exports'] = business;
business.credit_card_numbers = require("./credit_card_numbers");
business.credit_card_expiry_dates = require("./credit_card_expiry_dates");
business.credit_card_types = require("./credit_card_types");
},{"./credit_card_expiry_dates":59,"./credit_card_numbers":60,"./credit_card_types":61}],63:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####"
];
},{}],64:[function(require,module,exports){
var cell_phone = {};
module['exports'] = cell_phone;
cell_phone.formats = require("./formats");
},{"./formats":63}],65:[function(require,module,exports){
module["exports"] = [
"red",
"green",
"blue",
"yellow",
"purple",
"mint green",
"teal",
"white",
"black",
"orange",
"pink",
"grey",
"maroon",
"violet",
"turquoise",
"tan",
"sky blue",
"salmon",
"plum",
"orchid",
"olive",
"magenta",
"lime",
"ivory",
"indigo",
"gold",
"fuchsia",
"cyan",
"azure",
"lavender",
"silver"
];
},{}],66:[function(require,module,exports){
module["exports"] = [
"Books",
"Movies",
"Music",
"Games",
"Electronics",
"Computers",
"Home",
"Garden",
"Tools",
"Grocery",
"Health",
"Beauty",
"Toys",
"Kids",
"Baby",
"Clothing",
"Shoes",
"Jewelery",
"Sports",
"Outdoors",
"Automotive",
"Industrial"
];
},{}],67:[function(require,module,exports){
var commerce = {};
module['exports'] = commerce;
commerce.color = require("./color");
commerce.department = require("./department");
commerce.product_name = require("./product_name");
},{"./color":65,"./department":66,"./product_name":68}],68:[function(require,module,exports){
module["exports"] = {
"adjective": [
"Small",
"Ergonomic",
"Rustic",
"Intelligent",
"Gorgeous",
"Incredible",
"Fantastic",
"Practical",
"Sleek",
"Awesome",
"Generic",
"Handcrafted",
"Handmade",
"Licensed",
"Refined",
"Unbranded",
"Tasty"
],
"material": [
"Steel",
"Wooden",
"Concrete",
"Plastic",
"Cotton",
"Granite",
"Rubber",
"Metal",
"Soft",
"Fresh",
"Frozen"
],
"product": [
"Chair",
"Car",
"Computer",
"Keyboard",
"Mouse",
"Bike",
"Ball",
"Gloves",
"Pants",
"Shirt",
"Table",
"Shoes",
"Hat",
"Towels",
"Soap",
"Tuna",
"Chicken",
"Fish",
"Cheese",
"Bacon",
"Pizza",
"Salad",
"Sausages",
"Chips"
]
};
},{}],69:[function(require,module,exports){
module["exports"] = [
"Adaptive",
"Advanced",
"Ameliorated",
"Assimilated",
"Automated",
"Balanced",
"Business-focused",
"Centralized",
"Cloned",
"Compatible",
"Configurable",
"Cross-group",
"Cross-platform",
"Customer-focused",
"Customizable",
"Decentralized",
"De-engineered",
"Devolved",
"Digitized",
"Distributed",
"Diverse",
"Down-sized",
"Enhanced",
"Enterprise-wide",
"Ergonomic",
"Exclusive",
"Expanded",
"Extended",
"Face to face",
"Focused",
"Front-line",
"Fully-configurable",
"Function-based",
"Fundamental",
"Future-proofed",
"Grass-roots",
"Horizontal",
"Implemented",
"Innovative",
"Integrated",
"Intuitive",
"Inverse",
"Managed",
"Mandatory",
"Monitored",
"Multi-channelled",
"Multi-lateral",
"Multi-layered",
"Multi-tiered",
"Networked",
"Object-based",
"Open-architected",
"Open-source",
"Operative",
"Optimized",
"Optional",
"Organic",
"Organized",
"Persevering",
"Persistent",
"Phased",
"Polarised",
"Pre-emptive",
"Proactive",
"Profit-focused",
"Profound",
"Programmable",
"Progressive",
"Public-key",
"Quality-focused",
"Reactive",
"Realigned",
"Re-contextualized",
"Re-engineered",
"Reduced",
"Reverse-engineered",
"Right-sized",
"Robust",
"Seamless",
"Secured",
"Self-enabling",
"Sharable",
"Stand-alone",
"Streamlined",
"Switchable",
"Synchronised",
"Synergistic",
"Synergized",
"Team-oriented",
"Total",
"Triple-buffered",
"Universal",
"Up-sized",
"Upgradable",
"User-centric",
"User-friendly",
"Versatile",
"Virtual",
"Visionary",
"Vision-oriented"
];
},{}],70:[function(require,module,exports){
module["exports"] = [
"clicks-and-mortar",
"value-added",
"vertical",
"proactive",
"robust",
"revolutionary",
"scalable",
"leading-edge",
"innovative",
"intuitive",
"strategic",
"e-business",
"mission-critical",
"sticky",
"one-to-one",
"24/7",
"end-to-end",
"global",
"B2B",
"B2C",
"granular",
"frictionless",
"virtual",
"viral",
"dynamic",
"24/365",
"best-of-breed",
"killer",
"magnetic",
"bleeding-edge",
"web-enabled",
"interactive",
"dot-com",
"sexy",
"back-end",
"real-time",
"efficient",
"front-end",
"distributed",
"seamless",
"extensible",
"turn-key",
"world-class",
"open-source",
"cross-platform",
"cross-media",
"synergistic",
"bricks-and-clicks",
"out-of-the-box",
"enterprise",
"integrated",
"impactful",
"wireless",
"transparent",
"next-generation",
"cutting-edge",
"user-centric",
"visionary",
"customized",
"ubiquitous",
"plug-and-play",
"collaborative",
"compelling",
"holistic",
"rich"
];
},{}],71:[function(require,module,exports){
module["exports"] = [
"synergies",
"web-readiness",
"paradigms",
"markets",
"partnerships",
"infrastructures",
"platforms",
"initiatives",
"channels",
"eyeballs",
"communities",
"ROI",
"solutions",
"e-tailers",
"e-services",
"action-items",
"portals",
"niches",
"technologies",
"content",
"vortals",
"supply-chains",
"convergence",
"relationships",
"architectures",
"interfaces",
"e-markets",
"e-commerce",
"systems",
"bandwidth",
"infomediaries",
"models",
"mindshare",
"deliverables",
"users",
"schemas",
"networks",
"applications",
"metrics",
"e-business",
"functionalities",
"experiences",
"web services",
"methodologies"
];
},{}],72:[function(require,module,exports){
module["exports"] = [
"implement",
"utilize",
"integrate",
"streamline",
"optimize",
"evolve",
"transform",
"embrace",
"enable",
"orchestrate",
"leverage",
"reinvent",
"aggregate",
"architect",
"enhance",
"incentivize",
"morph",
"empower",
"envisioneer",
"monetize",
"harness",
"facilitate",
"seize",
"disintermediate",
"synergize",
"strategize",
"deploy",
"brand",
"grow",
"target",
"syndicate",
"synthesize",
"deliver",
"mesh",
"incubate",
"engage",
"maximize",
"benchmark",
"expedite",
"reintermediate",
"whiteboard",
"visualize",
"repurpose",
"innovate",
"scale",
"unleash",
"drive",
"extend",
"engineer",
"revolutionize",
"generate",
"exploit",
"transition",
"e-enable",
"iterate",
"cultivate",
"matrix",
"productize",
"redefine",
"recontextualize"
];
},{}],73:[function(require,module,exports){
module["exports"] = [
"24 hour",
"24/7",
"3rd generation",
"4th generation",
"5th generation",
"6th generation",
"actuating",
"analyzing",
"asymmetric",
"asynchronous",
"attitude-oriented",
"background",
"bandwidth-monitored",
"bi-directional",
"bifurcated",
"bottom-line",
"clear-thinking",
"client-driven",
"client-server",
"coherent",
"cohesive",
"composite",
"context-sensitive",
"contextually-based",
"content-based",
"dedicated",
"demand-driven",
"didactic",
"directional",
"discrete",
"disintermediate",
"dynamic",
"eco-centric",
"empowering",
"encompassing",
"even-keeled",
"executive",
"explicit",
"exuding",
"fault-tolerant",
"foreground",
"fresh-thinking",
"full-range",
"global",
"grid-enabled",
"heuristic",
"high-level",
"holistic",
"homogeneous",
"human-resource",
"hybrid",
"impactful",
"incremental",
"intangible",
"interactive",
"intermediate",
"leading edge",
"local",
"logistical",
"maximized",
"methodical",
"mission-critical",
"mobile",
"modular",
"motivating",
"multimedia",
"multi-state",
"multi-tasking",
"national",
"needs-based",
"neutral",
"next generation",
"non-volatile",
"object-oriented",
"optimal",
"optimizing",
"radical",
"real-time",
"reciprocal",
"regional",
"responsive",
"scalable",
"secondary",
"solution-oriented",
"stable",
"static",
"systematic",
"systemic",
"system-worthy",
"tangible",
"tertiary",
"transitional",
"uniform",
"upward-trending",
"user-facing",
"value-added",
"web-enabled",
"well-modulated",
"zero administration",
"zero defect",
"zero tolerance"
];
},{}],74:[function(require,module,exports){
var company = {};
module['exports'] = company;
company.suffix = require("./suffix");
company.adjective = require("./adjective");
company.descriptor = require("./descriptor");
company.noun = require("./noun");
company.bs_verb = require("./bs_verb");
company.bs_adjective = require("./bs_adjective");
company.bs_noun = require("./bs_noun");
company.name = require("./name");
},{"./adjective":69,"./bs_adjective":70,"./bs_noun":71,"./bs_verb":72,"./descriptor":73,"./name":75,"./noun":76,"./suffix":77}],75:[function(require,module,exports){
module["exports"] = [
"#{Name.last_name} #{suffix}",
"#{Name.last_name}-#{Name.last_name}",
"#{Name.last_name}, #{Name.last_name} and #{Name.last_name}"
];
},{}],76:[function(require,module,exports){
module["exports"] = [
"ability",
"access",
"adapter",
"algorithm",
"alliance",
"analyzer",
"application",
"approach",
"architecture",
"archive",
"artificial intelligence",
"array",
"attitude",
"benchmark",
"budgetary management",
"capability",
"capacity",
"challenge",
"circuit",
"collaboration",
"complexity",
"concept",
"conglomeration",
"contingency",
"core",
"customer loyalty",
"database",
"data-warehouse",
"definition",
"emulation",
"encoding",
"encryption",
"extranet",
"firmware",
"flexibility",
"focus group",
"forecast",
"frame",
"framework",
"function",
"functionalities",
"Graphic Interface",
"groupware",
"Graphical User Interface",
"hardware",
"help-desk",
"hierarchy",
"hub",
"implementation",
"info-mediaries",
"infrastructure",
"initiative",
"installation",
"instruction set",
"interface",
"internet solution",
"intranet",
"knowledge user",
"knowledge base",
"local area network",
"leverage",
"matrices",
"matrix",
"methodology",
"middleware",
"migration",
"model",
"moderator",
"monitoring",
"moratorium",
"neural-net",
"open architecture",
"open system",
"orchestration",
"paradigm",
"parallelism",
"policy",
"portal",
"pricing structure",
"process improvement",
"product",
"productivity",
"project",
"projection",
"protocol",
"secured line",
"service-desk",
"software",
"solution",
"standardization",
"strategy",
"structure",
"success",
"superstructure",
"support",
"synergy",
"system engine",
"task-force",
"throughput",
"time-frame",
"toolset",
"utilisation",
"website",
"workforce"
];
},{}],77:[function(require,module,exports){
module["exports"] = [
"Inc",
"and Sons",
"LLC",
"Group"
];
},{}],78:[function(require,module,exports){
module["exports"] = [
"/34##-######-####L/",
"/37##-######-####L/"
];
},{}],79:[function(require,module,exports){
module["exports"] = [
"/30[0-5]#-######-###L/",
"/368#-######-###L/"
];
},{}],80:[function(require,module,exports){
module["exports"] = [
"/6011-####-####-###L/",
"/65##-####-####-###L/",
"/64[4-9]#-####-####-###L/",
"/6011-62##-####-####-###L/",
"/65##-62##-####-####-###L/",
"/64[4-9]#-62##-####-####-###L/"
];
},{}],81:[function(require,module,exports){
var credit_card = {};
module['exports'] = credit_card;
credit_card.visa = require("./visa");
credit_card.mastercard = require("./mastercard");
credit_card.discover = require("./discover");
credit_card.american_express = require("./american_express");
credit_card.diners_club = require("./diners_club");
credit_card.jcb = require("./jcb");
credit_card.switch = require("./switch");
credit_card.solo = require("./solo");
credit_card.maestro = require("./maestro");
credit_card.laser = require("./laser");
},{"./american_express":78,"./diners_club":79,"./discover":80,"./jcb":82,"./laser":83,"./maestro":84,"./mastercard":85,"./solo":86,"./switch":87,"./visa":88}],82:[function(require,module,exports){
module["exports"] = [
"/3528-####-####-###L/",
"/3529-####-####-###L/",
"/35[3-8]#-####-####-###L/"
];
},{}],83:[function(require,module,exports){
module["exports"] = [
"/6304###########L/",
"/6706###########L/",
"/6771###########L/",
"/6709###########L/",
"/6304#########{5,6}L/",
"/6706#########{5,6}L/",
"/6771#########{5,6}L/",
"/6709#########{5,6}L/"
];
},{}],84:[function(require,module,exports){
module["exports"] = [
"/50#{9,16}L/",
"/5[6-8]#{9,16}L/",
"/56##{9,16}L/"
];
},{}],85:[function(require,module,exports){
module["exports"] = [
"/5[1-5]##-####-####-###L/",
"/6771-89##-####-###L/"
];
},{}],86:[function(require,module,exports){
module["exports"] = [
"/6767-####-####-###L/",
"/6767-####-####-####-#L/",
"/6767-####-####-####-##L/"
];
},{}],87:[function(require,module,exports){
module["exports"] = [
"/6759-####-####-###L/",
"/6759-####-####-####-#L/",
"/6759-####-####-####-##L/"
];
},{}],88:[function(require,module,exports){
module["exports"] = [
"/4###########L/",
"/4###-####-####-###L/"
];
},{}],89:[function(require,module,exports){
var date = {};
module["exports"] = date;
date.month = require("./month");
date.weekday = require("./weekday");
},{"./month":90,"./weekday":91}],90:[function(require,module,exports){
// Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1799
module["exports"] = {
wide: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
// Property "wide_context" is optional, if not set then "wide" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
wide_context: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
abbr: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
// Property "abbr_context" is optional, if not set then "abbr" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
abbr_context: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
};
},{}],91:[function(require,module,exports){
// Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1847
module["exports"] = {
wide: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
// Property "wide_context" is optional, if not set then "wide" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
wide_context: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
abbr: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
// Property "abbr_context" is optional, if not set then "abbr" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
abbr_context: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
]
};
},{}],92:[function(require,module,exports){
module["exports"] = [
"Checking",
"Savings",
"Money Market",
"Investment",
"Home Loan",
"Credit Card",
"Auto Loan",
"Personal Loan"
];
},{}],93:[function(require,module,exports){
module["exports"] = {
"UAE Dirham": {
"code": "AED",
"symbol": ""
},
"Afghani": {
"code": "AFN",
"symbol": "؋"
},
"Lek": {
"code": "ALL",
"symbol": "Lek"
},
"Armenian Dram": {
"code": "AMD",
"symbol": ""
},
"Netherlands Antillian Guilder": {
"code": "ANG",
"symbol": "ƒ"
},
"Kwanza": {
"code": "AOA",
"symbol": ""
},
"Argentine Peso": {
"code": "ARS",
"symbol": "$"
},
"Australian Dollar": {
"code": "AUD",
"symbol": "$"
},
"Aruban Guilder": {
"code": "AWG",
"symbol": "ƒ"
},
"Azerbaijanian Manat": {
"code": "AZN",
"symbol": "ман"
},
"Convertible Marks": {
"code": "BAM",
"symbol": "KM"
},
"Barbados Dollar": {
"code": "BBD",
"symbol": "$"
},
"Taka": {
"code": "BDT",
"symbol": ""
},
"Bulgarian Lev": {
"code": "BGN",
"symbol": "лв"
},
"Bahraini Dinar": {
"code": "BHD",
"symbol": ""
},
"Burundi Franc": {
"code": "BIF",
"symbol": ""
},
"Bermudian Dollar (customarily known as Bermuda Dollar)": {
"code": "BMD",
"symbol": "$"
},
"Brunei Dollar": {
"code": "BND",
"symbol": "$"
},
"Boliviano Mvdol": {
"code": "BOB BOV",
"symbol": "$b"
},
"Brazilian Real": {
"code": "BRL",
"symbol": "R$"
},
"Bahamian Dollar": {
"code": "BSD",
"symbol": "$"
},
"Pula": {
"code": "BWP",
"symbol": "P"
},
"Belarussian Ruble": {
"code": "BYR",
"symbol": "p."
},
"Belize Dollar": {
"code": "BZD",
"symbol": "BZ$"
},
"Canadian Dollar": {
"code": "CAD",
"symbol": "$"
},
"Congolese Franc": {
"code": "CDF",
"symbol": ""
},
"Swiss Franc": {
"code": "CHF",
"symbol": "CHF"
},
"Chilean Peso Unidades de fomento": {
"code": "CLP CLF",
"symbol": "$"
},
"Yuan Renminbi": {
"code": "CNY",
"symbol": "¥"
},
"Colombian Peso Unidad de Valor Real": {
"code": "COP COU",
"symbol": "$"
},
"Costa Rican Colon": {
"code": "CRC",
"symbol": "₡"
},
"Cuban Peso Peso Convertible": {
"code": "CUP CUC",
"symbol": "₱"
},
"Cape Verde Escudo": {
"code": "CVE",
"symbol": ""
},
"Czech Koruna": {
"code": "CZK",
"symbol": "Kč"
},
"Djibouti Franc": {
"code": "DJF",
"symbol": ""
},
"Danish Krone": {
"code": "DKK",
"symbol": "kr"
},
"Dominican Peso": {
"code": "DOP",
"symbol": "RD$"
},
"Algerian Dinar": {
"code": "DZD",
"symbol": ""
},
"Kroon": {
"code": "EEK",
"symbol": ""
},
"Egyptian Pound": {
"code": "EGP",
"symbol": "£"
},
"Nakfa": {
"code": "ERN",
"symbol": ""
},
"Ethiopian Birr": {
"code": "ETB",
"symbol": ""
},
"Euro": {
"code": "EUR",
"symbol": "€"
},
"Fiji Dollar": {
"code": "FJD",
"symbol": "$"
},
"Falkland Islands Pound": {
"code": "FKP",
"symbol": "£"
},
"Pound Sterling": {
"code": "GBP",
"symbol": "£"
},
"Lari": {
"code": "GEL",
"symbol": ""
},
"Cedi": {
"code": "GHS",
"symbol": ""
},
"Gibraltar Pound": {
"code": "GIP",
"symbol": "£"
},
"Dalasi": {
"code": "GMD",
"symbol": ""
},
"Guinea Franc": {
"code": "GNF",
"symbol": ""
},
"Quetzal": {
"code": "GTQ",
"symbol": "Q"
},
"Guyana Dollar": {
"code": "GYD",
"symbol": "$"
},
"Hong Kong Dollar": {
"code": "HKD",
"symbol": "$"
},
"Lempira": {
"code": "HNL",
"symbol": "L"
},
"Croatian Kuna": {
"code": "HRK",
"symbol": "kn"
},
"Gourde US Dollar": {
"code": "HTG USD",
"symbol": ""
},
"Forint": {
"code": "HUF",
"symbol": "Ft"
},
"Rupiah": {
"code": "IDR",
"symbol": "Rp"
},
"New Israeli Sheqel": {
"code": "ILS",
"symbol": "₪"
},
"Indian Rupee": {
"code": "INR",
"symbol": ""
},
"Indian Rupee Ngultrum": {
"code": "INR BTN",
"symbol": ""
},
"Iraqi Dinar": {
"code": "IQD",
"symbol": ""
},
"Iranian Rial": {
"code": "IRR",
"symbol": "﷼"
},
"Iceland Krona": {
"code": "ISK",
"symbol": "kr"
},
"Jamaican Dollar": {
"code": "JMD",
"symbol": "J$"
},
"Jordanian Dinar": {
"code": "JOD",
"symbol": ""
},
"Yen": {
"code": "JPY",
"symbol": "¥"
},
"Kenyan Shilling": {
"code": "KES",
"symbol": ""
},
"Som": {
"code": "KGS",
"symbol": "лв"
},
"Riel": {
"code": "KHR",
"symbol": "៛"
},
"Comoro Franc": {
"code": "KMF",
"symbol": ""
},
"North Korean Won": {
"code": "KPW",
"symbol": "₩"
},
"Won": {
"code": "KRW",
"symbol": "₩"
},
"Kuwaiti Dinar": {
"code": "KWD",
"symbol": ""
},
"Cayman Islands Dollar": {
"code": "KYD",
"symbol": "$"
},
"Tenge": {
"code": "KZT",
"symbol": "лв"
},
"Kip": {
"code": "LAK",
"symbol": "₭"
},
"Lebanese Pound": {
"code": "LBP",
"symbol": "£"
},
"Sri Lanka Rupee": {
"code": "LKR",
"symbol": "₨"
},
"Liberian Dollar": {
"code": "LRD",
"symbol": "$"
},
"Lithuanian Litas": {
"code": "LTL",
"symbol": "Lt"
},
"Latvian Lats": {
"code": "LVL",
"symbol": "Ls"
},
"Libyan Dinar": {
"code": "LYD",
"symbol": ""
},
"Moroccan Dirham": {
"code": "MAD",
"symbol": ""
},
"Moldovan Leu": {
"code": "MDL",
"symbol": ""
},
"Malagasy Ariary": {
"code": "MGA",
"symbol": ""
},
"Denar": {
"code": "MKD",
"symbol": "ден"
},
"Kyat": {
"code": "MMK",
"symbol": ""
},
"Tugrik": {
"code": "MNT",
"symbol": "₮"
},
"Pataca": {
"code": "MOP",
"symbol": ""
},
"Ouguiya": {
"code": "MRO",
"symbol": ""
},
"Mauritius Rupee": {
"code": "MUR",
"symbol": "₨"
},
"Rufiyaa": {
"code": "MVR",
"symbol": ""
},
"Kwacha": {
"code": "MWK",
"symbol": ""
},
"Mexican Peso Mexican Unidad de Inversion (UDI)": {
"code": "MXN MXV",
"symbol": "$"
},
"Malaysian Ringgit": {
"code": "MYR",
"symbol": "RM"
},
"Metical": {
"code": "MZN",
"symbol": "MT"
},
"Naira": {
"code": "NGN",
"symbol": "₦"
},
"Cordoba Oro": {
"code": "NIO",
"symbol": "C$"
},
"Norwegian Krone": {
"code": "NOK",
"symbol": "kr"
},
"Nepalese Rupee": {
"code": "NPR",
"symbol": "₨"
},
"New Zealand Dollar": {
"code": "NZD",
"symbol": "$"
},
"Rial Omani": {
"code": "OMR",
"symbol": "﷼"
},
"Balboa US Dollar": {
"code": "PAB USD",
"symbol": "B/."
},
"Nuevo Sol": {
"code": "PEN",
"symbol": "S/."
},
"Kina": {
"code": "PGK",
"symbol": ""
},
"Philippine Peso": {
"code": "PHP",
"symbol": "Php"
},
"Pakistan Rupee": {
"code": "PKR",
"symbol": "₨"
},
"Zloty": {
"code": "PLN",
"symbol": "zł"
},
"Guarani": {
"code": "PYG",
"symbol": "Gs"
},
"Qatari Rial": {
"code": "QAR",
"symbol": "﷼"
},
"New Leu": {
"code": "RON",
"symbol": "lei"
},
"Serbian Dinar": {
"code": "RSD",
"symbol": "Дин."
},
"Russian Ruble": {
"code": "RUB",
"symbol": "руб"
},
"Rwanda Franc": {
"code": "RWF",
"symbol": ""
},
"Saudi Riyal": {
"code": "SAR",
"symbol": "﷼"
},
"Solomon Islands Dollar": {
"code": "SBD",
"symbol": "$"
},
"Seychelles Rupee": {
"code": "SCR",
"symbol": "₨"
},
"Sudanese Pound": {
"code": "SDG",
"symbol": ""
},
"Swedish Krona": {
"code": "SEK",
"symbol": "kr"
},
"Singapore Dollar": {
"code": "SGD",
"symbol": "$"
},
"Saint Helena Pound": {
"code": "SHP",
"symbol": "£"
},
"Leone": {
"code": "SLL",
"symbol": ""
},
"Somali Shilling": {
"code": "SOS",
"symbol": "S"
},
"Surinam Dollar": {
"code": "SRD",
"symbol": "$"
},
"Dobra": {
"code": "STD",
"symbol": ""
},
"El Salvador Colon US Dollar": {
"code": "SVC USD",
"symbol": "$"
},
"Syrian Pound": {
"code": "SYP",
"symbol": "£"
},
"Lilangeni": {
"code": "SZL",
"symbol": ""
},
"Baht": {
"code": "THB",
"symbol": "฿"
},
"Somoni": {
"code": "TJS",
"symbol": ""
},
"Manat": {
"code": "TMT",
"symbol": ""
},
"Tunisian Dinar": {
"code": "TND",
"symbol": ""
},
"Pa'anga": {
"code": "TOP",
"symbol": ""
},
"Turkish Lira": {
"code": "TRY",
"symbol": "TL"
},
"Trinidad and Tobago Dollar": {
"code": "TTD",
"symbol": "TT$"
},
"New Taiwan Dollar": {
"code": "TWD",
"symbol": "NT$"
},
"Tanzanian Shilling": {
"code": "TZS",
"symbol": ""
},
"Hryvnia": {
"code": "UAH",
"symbol": "₴"
},
"Uganda Shilling": {
"code": "UGX",
"symbol": ""
},
"US Dollar": {
"code": "USD",
"symbol": "$"
},
"Peso Uruguayo Uruguay Peso en Unidades Indexadas": {
"code": "UYU UYI",
"symbol": "$U"
},
"Uzbekistan Sum": {
"code": "UZS",
"symbol": "лв"
},
"Bolivar Fuerte": {
"code": "VEF",
"symbol": "Bs"
},
"Dong": {
"code": "VND",
"symbol": "₫"
},
"Vatu": {
"code": "VUV",
"symbol": ""
},
"Tala": {
"code": "WST",
"symbol": ""
},
"CFA Franc BEAC": {
"code": "XAF",
"symbol": ""
},
"Silver": {
"code": "XAG",
"symbol": ""
},
"Gold": {
"code": "XAU",
"symbol": ""
},
"Bond Markets Units European Composite Unit (EURCO)": {
"code": "XBA",
"symbol": ""
},
"European Monetary Unit (E.M.U.-6)": {
"code": "XBB",
"symbol": ""
},
"European Unit of Account 9(E.U.A.-9)": {
"code": "XBC",
"symbol": ""
},
"European Unit of Account 17(E.U.A.-17)": {
"code": "XBD",
"symbol": ""
},
"East Caribbean Dollar": {
"code": "XCD",
"symbol": "$"
},
"SDR": {
"code": "XDR",
"symbol": ""
},
"UIC-Franc": {
"code": "XFU",
"symbol": ""
},
"CFA Franc BCEAO": {
"code": "XOF",
"symbol": ""
},
"Palladium": {
"code": "XPD",
"symbol": ""
},
"CFP Franc": {
"code": "XPF",
"symbol": ""
},
"Platinum": {
"code": "XPT",
"symbol": ""
},
"Codes specifically reserved for testing purposes": {
"code": "XTS",
"symbol": ""
},
"Yemeni Rial": {
"code": "YER",
"symbol": "﷼"
},
"Rand": {
"code": "ZAR",
"symbol": "R"
},
"Rand Loti": {
"code": "ZAR LSL",
"symbol": ""
},
"Rand Namibia Dollar": {
"code": "ZAR NAD",
"symbol": ""
},
"Zambian Kwacha": {
"code": "ZMK",
"symbol": ""
},
"Zimbabwe Dollar": {
"code": "ZWL",
"symbol": ""
}
};
},{}],94:[function(require,module,exports){
var finance = {};
module['exports'] = finance;
finance.account_type = require("./account_type");
finance.transaction_type = require("./transaction_type");
finance.currency = require("./currency");
},{"./account_type":92,"./currency":93,"./transaction_type":95}],95:[function(require,module,exports){
module["exports"] = [
"deposit",
"withdrawal",
"payment",
"invoice"
];
},{}],96:[function(require,module,exports){
module["exports"] = [
"TCP",
"HTTP",
"SDD",
"RAM",
"GB",
"CSS",
"SSL",
"AGP",
"SQL",
"FTP",
"PCI",
"AI",
"ADP",
"RSS",
"XML",
"EXE",
"COM",
"HDD",
"THX",
"SMTP",
"SMS",
"USB",
"PNG",
"SAS",
"IB",
"SCSI",
"JSON",
"XSS",
"JBOD"
];
},{}],97:[function(require,module,exports){
module["exports"] = [
"auxiliary",
"primary",
"back-end",
"digital",
"open-source",
"virtual",
"cross-platform",
"redundant",
"online",
"haptic",
"multi-byte",
"bluetooth",
"wireless",
"1080p",
"neural",
"optical",
"solid state",
"mobile"
];
},{}],98:[function(require,module,exports){
var hacker = {};
module['exports'] = hacker;
hacker.abbreviation = require("./abbreviation");
hacker.adjective = require("./adjective");
hacker.noun = require("./noun");
hacker.verb = require("./verb");
hacker.ingverb = require("./ingverb");
},{"./abbreviation":96,"./adjective":97,"./ingverb":99,"./noun":100,"./verb":101}],99:[function(require,module,exports){
module["exports"] = [
"backing up",
"bypassing",
"hacking",
"overriding",
"compressing",
"copying",
"navigating",
"indexing",
"connecting",
"generating",
"quantifying",
"calculating",
"synthesizing",
"transmitting",
"programming",
"parsing"
];
},{}],100:[function(require,module,exports){
module["exports"] = [
"driver",
"protocol",
"bandwidth",
"panel",
"microchip",
"program",
"port",
"card",
"array",
"interface",
"system",
"sensor",
"firewall",
"hard drive",
"pixel",
"alarm",
"feed",
"monitor",
"application",
"transmitter",
"bus",
"circuit",
"capacitor",
"matrix"
];
},{}],101:[function(require,module,exports){
module["exports"] = [
"back up",
"bypass",
"hack",
"override",
"compress",
"copy",
"navigate",
"index",
"connect",
"generate",
"quantify",
"calculate",
"synthesize",
"input",
"transmit",
"program",
"reboot",
"parse"
];
},{}],102:[function(require,module,exports){
var en = {};
module['exports'] = en;
en.title = "English";
en.separator = " & ";
en.address = require("./address");
en.credit_card = require("./credit_card");
en.company = require("./company");
en.internet = require("./internet");
en.lorem = require("./lorem");
en.name = require("./name");
en.phone_number = require("./phone_number");
en.cell_phone = require("./cell_phone");
en.business = require("./business");
en.commerce = require("./commerce");
en.team = require("./team");
en.hacker = require("./hacker");
en.app = require("./app");
en.finance = require("./finance");
en.date = require("./date");
},{"./address":45,"./app":56,"./business":62,"./cell_phone":64,"./commerce":67,"./company":74,"./credit_card":81,"./date":89,"./finance":94,"./hacker":98,"./internet":106,"./lorem":107,"./name":111,"./phone_number":118,"./team":120}],103:[function(require,module,exports){
module["exports"] = [
"https://s3.amazonaws.com/uifaces/faces/twitter/jarjan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mahdif/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sprayaga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ruzinav/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Skyhartman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/moscoz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kurafire/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/91bilal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/igorgarybaldi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/malykhinv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joelhelin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kushsolitary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/snowshade/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/areus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/holdenweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heyimjuani/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/envex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/unterdreht/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/collegeman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peejfancher/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andyisonline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ultragex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fuck_you_two/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmetalpbalkan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Stievius/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kerem/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osvaldas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelceballos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thierrykoblentz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/catarino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/weglov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandclay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flame_kaizar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmetsulek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicolasfolliot/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jayrobinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorerixon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolage/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michzen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markjenkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicolai_larsen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/noxdzine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alagoon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/idiot/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mizko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chadengle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mutlu82/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/simobenso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vocino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guiiipontes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/soyjavi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshaustin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tomaslau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/VinThomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ManikRathee/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/langate/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cemshid/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leemunroe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_shahedk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BillSKenney/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/divya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshhemsley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sindresorhus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/soffes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/9lessons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/linux29/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Chakintosh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anaami/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joreira/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shadeed9/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottkclark/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jedbridges/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salleedesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marakasina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ariil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BrianPurkiss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelmartinho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bublienko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/devankoshal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ZacharyZorbas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timmillwood/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshuasortino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/damenleeturks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tomas_janousek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herrhaase/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/RussellBishop/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brajeshwar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nachtmeister/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cbracco/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bermonpainter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdullindenis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isacosta/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/suprb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yalozhkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chandlervdw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamgarth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_victa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/commadelimited/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/roybarberuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/axel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ffbel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/syropian/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ankitind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/traneblow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flashmurphy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ChrisFarina78/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baliomega/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saschamt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jm_denis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anoff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kennyadr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chatyrko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dingyi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mds/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terryxlife/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaroni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kinday/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prrstn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eduardostuart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhilipsiva/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/GavicoInd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rohixx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/blakesimkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leeiio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tjrus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uberschizo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kylefoundry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/claudioguglieri/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ripplemdk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/exentrich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jakemoore/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joaoedumedeiros/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/poormini/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tereshenkov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/keryilmaz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haydn_woods/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rude/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/llun/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sgaurav_baghel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jamiebrittain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/badlittleduck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pifagor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/agromov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/erwanhesry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/diesellaws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremiaha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/koridhandy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chaensel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewcohen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smaczny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gonzalorobaina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nandini_m/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sydlawrence/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cdharrison/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tgerken/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lewisainslie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charliecwaite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robbschiller/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flexrs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattdetails/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/raquelwilson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karsh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrmartineau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/opnsrce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hgharrygo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maximseshuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxalex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samihah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chanpory/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sharvin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josemarques/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jefffis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/krystalfister/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lokesh_coder/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thedamianhdez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dpmachado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/funwatercat/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timothycd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ivanfilipovbg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/picard102/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcobarbosa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/krasnoukhov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/g3d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ademilter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rickdt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/operatino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bungiwan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hugomano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/logorado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dc_user/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/horaciobella/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/SlaapMe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teeragit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iqonicd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ilya_pestov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewarrow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ssiskind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/HenryHoffman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rdsaunders/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamsxu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/curiousoffice/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themadray/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michigangraham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kohette/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nickfratter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/runningskull/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madysondesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brenton_clarke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jennyshen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bradenhamm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kurtinc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amanruzaini/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyhaggard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Karimmove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaronalfred/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wtrsld/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jitachi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/therealmarvin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pmeissner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ooomz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chacky14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jesseddy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thinmatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shanehudson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akmur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/IsaryAmairani/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arthurholcombe1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andychipster/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/boxmodel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ehsandiary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/LucasPerdidao/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shalt0ni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/swaplord/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaelifa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/plbabin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guillemboti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arindam_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/renbyrd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thiagovernetti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jmillspaysbills/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikemai2awesome/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jervo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mekal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sta1ex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robergd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/felipecsl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrea211087/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/garand/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhooyenga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abovefunction/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pcridesagain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/randomlies/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BryanHorsey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heykenneth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dahparra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allthingssmitty/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danvernon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/beweinreich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/increase/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falvarad/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alxndrustinov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/souuf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/orkuncaylar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/AM_Kn2/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gearpixels/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bassamology/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vimarethomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kosmar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/SULiik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrjamesnoble/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/silvanmuhlemann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shaneIxD/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nacho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yigitpinarbasi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buzzusborne/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaronkwhite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rmlewisuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/giancarlon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nbirckel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d_nny_m_cher/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sdidonato/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/atariboy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abotap/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karalek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/psdesignuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ludwiczakpawel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nemanjaivanovic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baluli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmadajmi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vovkasolovev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samgrover/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derienzo777/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonathansimmons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nelsonjoyce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/S0ufi4n3/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xtopherpaul/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oaktreemedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nateschulte/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/findingjenny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/namankreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antonyzotov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/we_social/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leehambley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/solid_color/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abelcabans/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mbilderbach/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kkusaa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jordyvdboom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosgavina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pechkinator/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vc27/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rdbannon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/croakx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/suribbles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kerihenare/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/catadeleon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gcmorley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/duivvv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saschadroste/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorDubugras/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wintopia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattbilotti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/taylorling/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/megdraws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/meln1ks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mahmoudmetwally/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Silveredge9/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derekebradley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/happypeter1983/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/travis_arnold/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artem_kostenko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adobi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/daykiine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alek_djuric/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scips/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/miguelmendes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrhee/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alsobrooks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fronx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mcflydesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/santi_urso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allfordesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stayuber/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bertboerland/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marosholly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamnac/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cynthiasavard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/muringa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hiemil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jackiesaik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zacsnider/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iduuck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antjanus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aroon_sharma/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dshster/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thehacker/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelbrooksjr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryanmclaughlin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/clubb3rry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/taybenlor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xripunov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/myastro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adityasutomo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/digitalmaverick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hjartstrorn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itolmach/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vaughanmoffitt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdots/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isnifer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sergeysafonov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scrapdnb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrismj83/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vitorleal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sokaniwaal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zaki3d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/illyzoren/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mocabyte/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osmanince/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/djsherman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidhemphill/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/waghner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/necodymiconer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/praveen_vijaya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fabbrucci/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cliffseal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/travishines/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kuldarkalvik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Elt_n/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/phillapier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okseanjay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/id835559/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kudretkeskin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anjhero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/duck4fuck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scott_riley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/noufalibrahim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/h1brd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/borges_marcos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/devinhalladay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ciaranr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefooo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikebeecham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tonymillion/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshuaraichur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/irae/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petrangr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dmitriychuta/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charliegann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arashmanteghi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ainsleywagon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/svenlen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/faisalabid/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/beshur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlyson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dutchnadia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teddyzetterlund/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samuelkraft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aoimedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/toddrew/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/codepoet_ru/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artvavs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benoitboucart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jomarmen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolmarlopez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/creartinc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/homka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gaborenton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robinclediere/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maximsorokin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/plasticine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j2deme/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peachananr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kapaluccio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/de_ascanio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rikas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dawidwu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelcreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rpatey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/popey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rehatkathuria/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/the_purplebunny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/1markiz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ajaxy_ru/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dudestein/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oskarlevinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorstuber/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nehfy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vicivadeline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leandrovaranda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottgallant/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victor_haydin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sawrb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryhanhassan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amayvs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a_brixen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karolkrakowiak_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herkulano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geran7/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cggaurav/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chris_witko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lososina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/polarity/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattlat/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonburke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/constantx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teylorfeliz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craigelimeliah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rachelreveley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reabo101/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rahmeen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rickyyean/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j04ntoh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spbroma/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sebashton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jpenico/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/francis_vega/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oktayelipek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kikillo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fabbianz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/larrygerard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BroumiYoussef/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/0therplanet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mbilalsiddique1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ionuss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/grrr_nl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/liminha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rawdiggie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryandownie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sethlouey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pixage/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arpitnj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/switmer777/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josevnclch/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kanickairaj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/puzik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tbakdesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/besbujupi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/supjoey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lowie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/linkibol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/balintorosz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imcoding/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/agustincruiz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gusoto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thomasschrijer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/superoutman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kalmerrautam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gabrielizalo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gojeanyn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidbaldie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_vojto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/laurengray/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jydesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mymyboy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nellleo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marciotoledo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ninjad3m0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/to_soham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hasslunsford/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/muridrahhal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/levisan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/grahamkennery/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lepetitogre/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antongenkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nessoila/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amandabuzard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/safrankov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cocolero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dss49/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matt3224/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bluesix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/quailandquasar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/AlbertoCococi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lepinski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sementiy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhudobivnik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thibaut_re/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/olgary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shojberg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mtolokonnikov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bereto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/naupintos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wegotvices/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xadhix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/macxim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rodnylobos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madcampos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madebyvadim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bartoszdawydzik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/supervova/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markretzloff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vonachoo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/darylws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stevedesigner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mylesb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herbigt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/depaulawagner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geshan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gizmeedevil1991/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_scottburgess/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lisovsky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidsasda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artd_sign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/YoungCutlass/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mgonto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorquinn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osmond/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oksanafrewer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zauerkraut/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamkeithmason/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nitinhayaran/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lmjabreu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mandalareopens/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thinkleft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ponchomendivil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juamperro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brunodesign1206/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/caseycavanagh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/luxe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dotgridline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spedwig/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madewulf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattsapii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/helderleal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisstumph/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jayphen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nsamoylov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisvanderkooi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justme_timothyg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/otozk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prinzadi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gu5taf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cyril_gaillard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d_kobelyatsky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/daniloc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nwdsha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/romanbulah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/skkirilov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dvdwinden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dannol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thekevinjones/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jwalter14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timgthomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buddhasource/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxpiper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thatonetommy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/diansigitp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adrienths/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/klimmka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gkaam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derekcramer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jennyyo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xalionmalik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edhenderson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/keyuri85/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/roxanejammet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kimcool/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edkf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alessandroribe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jacksonlatka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lebronjennan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kostaspt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karlkanall/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/moynihan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danpliego/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saulihirvi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wesleytrankin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fjaguero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bowbrick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mashaaaaal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yassiryahya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dparrelli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fotomagin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aka_james/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/denisepires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iqbalperkasa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/martinansty/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jarsen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/r_oy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gabrielrosser/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/malgordon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlfairclough/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelabehsera/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pierrestoffe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enjoythetau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/loganjlambert/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rpeezy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyginnivan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michalhron/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/msveet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lingeswaran/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolsvein/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peter576/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reideiredale/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joeymurdah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/raphaelnikson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mvdheuvel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maxlinderman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/begreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/frankiefreesbie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robturlinckx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Talbi_ConSept/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/longlivemyword/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vanchesz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maiklam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hermanobrother/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rez___a/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregsqueeb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/greenbes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_ragzor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anthonysukow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fluidbrush/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dactrtr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jehnglynn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bergmartin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hugocornejo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_kkga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dzantievm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sawalazar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sovesove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonsgotwood/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/byryan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vytautas_a/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mizhgan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cicerobr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nilshelmersson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d33pthought/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davecraige/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nckjrvs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alexandermayes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jcubic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craigrcoles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bagawarman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rob_thomas10/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cofla/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maikelk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rtgibbons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/russell_baylis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhesslow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/codysanfilippo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/webtanya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madebybrenton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dcalonaci/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/perfectflow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jjsiii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saarabpreet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kumarrajan12123/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamsteffen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themikenagle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ceekaytweet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/larrybolt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/conspirator/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dallasbpeters/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n3dmax/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terpimost/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kirillz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/byrnecore/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j_drake_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/calebjoyce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hoangloi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tobysaxon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gofrasdesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dimaposnyy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tjisousa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okandungel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/billyroshan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oskamaya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/motionthinks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/knilob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ashocka18/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marrimo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bartjo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/omnizya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ernestsemerda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andreas_pr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edgarchris99/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thomasgeisen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gseguin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joannefournier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/demersdesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adammarsbar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nasirwd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n_tassone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/javorszky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themrdave/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yecidsm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicollerich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/canapud/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicoleglynn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/judzhin_miles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/designervzm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kianoshp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/evandrix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alterchuca/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhrubo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ma_tiax/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ssbb_me/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dorphern/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mauriolg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bruno_mart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mactopus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/the_winslet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joemdesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Shriiiiimp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jacobbennett/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nfedoroff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamglimy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allagringaus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aiiaiiaii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/olaolusoga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buryaknick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wim1k/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicklacke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a1chapone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/steynviljoen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/strikewan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryankirkman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewabogado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/doooon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jagan123/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ariffsetiawan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elenadissi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mwarkentin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thierrymeier_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/r_garcia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dmackerman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/borantula/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/konus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spacewood_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryuchi311/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/evanshajed/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tristanlegros/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shoaib253/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aislinnkelly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okcoker/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timpetricola/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sunshinedgirl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chadami/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleclarsoniv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nomidesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petebernardo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottiedude/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/millinet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imsoper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imammuht/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benjamin_knight/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nepdud/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joki4/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lanceguyatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bboy1895/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amywebbb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rweve/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haruintesettden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ricburton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nelshd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/batsirai/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/primozcigler/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jffgrdnr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/8d3k/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geneseleznev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/al_li/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/souperphly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mslarkina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/2fockus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cdavis565/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xiel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/turkutuuli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxward/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lebinoclard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gauravjassal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidmerrique/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mdsisto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewofficer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kojourin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dnirmal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mr_shiznit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aluisio_azevedo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cloudstudio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danvierich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alexivanichkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fran_mchamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/perretmagali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/betraydan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cadikkara/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matbeedotcom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremyworboys/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bpartridge/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelkoper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/silv3rgvn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alevizio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lawlbwoy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vitor376/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/desastrozo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thimo_cz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jasonmarkjones/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lhausermann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xravil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guischmitt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vigobronx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/panghal0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/miguelkooreman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/surgeonist/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/christianoliff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/caspergrl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamkarna/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ipavelek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pierre_nel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/y2graphic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sterlingrules/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elbuscainfo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bennyjien/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stushona/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/estebanuribe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/embrcecreations/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danillos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elliotlewis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charlesrpratt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladyn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emmeffess/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosblanco_eu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leonfedotov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rangafangs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chris_frees/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tgormtx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bryan_topham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jpscribbles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mighty55/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carbontwelve/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isaacfifth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamjdeleon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/snowwrite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/barputro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/drewbyreese/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sachacorazzi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bistrianiosip/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/magoo04/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pehamondello/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yayteejay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a_harris88/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/algunsanabria/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zforrester/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ovall/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosjgsousa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geobikas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ah_lice/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/looneydoodle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nerdgr8/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ddggccaa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zackeeler/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/normanbox/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/el_fuertisimo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ismail_biltagi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juangomezw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jnmnrd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/patrickcoombe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryanjohnson_me/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markolschesky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeffgolenski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kvasnic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lindseyzilla/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gauchomatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/afusinatto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevinoh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okansurreel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamawesomeface/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emileboudeling/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arishi_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juanmamartinez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wikiziner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danthms/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mkginfo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terrorpixel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/curiousonaut/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prheemo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelcolenso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/foczzi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/martip07/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thaodang17/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johncafazza/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robinlayfield/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/franciscoamk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdulhyeuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marklamb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edobene/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andresenfredrik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikaeljorhult/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisslowik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vinciarts/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/meelford/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elliotnolten/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yehudab/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vijaykarthik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bfrohs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josep_martins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/attacks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sur4dye/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tumski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/instalox/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mangosango/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/paulfarino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kazaky999/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kiwiupover/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nvkznemo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tom_even/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ratbus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/woodsman001/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshmedeski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thewillbeard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/psaikali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joe_black/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleinadsays/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcusgorillius/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hota_v/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jghyllebert/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shinze/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/janpalounek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremiespoken/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/her_ruu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dansowter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/felipeapiress/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/magugzbrand2d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/posterjob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nathalie_fs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bobbytwoshoes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dreizle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremymouton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elisabethkjaer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/notbadart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mohanrohith/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jlsolerdeltoro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itskawsar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/slowspock/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zvchkelly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wiljanslofstra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craighenneberry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/trubeatto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juaumlol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samscouto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BenouarradeM/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gipsy_raf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/netonet_il/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arkokoley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itsajimithing/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smalonso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victordeanda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_dwite_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/richardgarretts/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregrwilkinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anatolinicolae/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lu4sh1i/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefanotirloni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ostirbu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/darcystonge/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/naitanamoreno/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelcomiskey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adhiardana/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcomano_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidcazalis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falconerie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregkilian/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bcrad/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bolzanmarco/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/low_res/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vlajki/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petar_prog/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonkspr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akmalfikri/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mfacchinello/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/atanism/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/harry_sistalam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/murrayswift/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bobwassermann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gavr1l0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madshensel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mr_subtle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/deviljho_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salimianoff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joetruesdell/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/twittypork/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/airskylar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dnezkumar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dgajjar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cherif_b/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/louis_currie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/deeenright/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cybind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eyronn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vickyshits/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sweetdelisa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cboller1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andresdjasso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/melvindidit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andysolomon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thaisselenator_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lvovenok/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/giuliusa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/belyaev_rs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/overcloacked/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kamal_chaneman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/incubo82/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hellofeverrrr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhaligowski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sunlandictwin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bu7921/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andytlaw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremery/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/finchjke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/manigm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/umurgdk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottfeltham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ganserene/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mutu_krish/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jodytaggart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ntfblog/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tanveerrao/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hfalucas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alxleroydeval/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kucingbelang4/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bargaorobalo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/colgruv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stalewine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kylefrost/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baumannzone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelcolberg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sachingawas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jjshaw14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ramanathan_pdy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johndezember/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nilshoenson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonmorreale/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nutzumi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonflatsoda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sergeyalmone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/klefue/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kirangopal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baumann_alex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matthewkay_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jay_wilburn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shesgared/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/apriendeau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johnriordan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wake_gs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleksitappura/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emsgulam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xilantra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imomenui/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sircalebgrove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/newbrushes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hsinyo23/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/m4rio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/katiemdaly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/s4f1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ecommerceil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marlinjayakody/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/swooshycueb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sangdth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coderdiaz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bluefx_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eugeneeweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dgclegg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n1ght_coder/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dixchen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/blakehawksworth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/trueblood_33/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hai_ninh_nguyen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marclgonzales/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yesmeck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stephcoue/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/doronmalki/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ruehldesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anasnakawa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kijanmaharjan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wearesavas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefvdham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tweetubhai/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alecarpentier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fiterik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antonyryndya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d00maz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/theonlyzeke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/missaaamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/manekenthe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reetajayendra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremyshimko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrgraham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefanozoffoli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/overra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrebay007/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shvelo96/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pyronite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thedjpetersen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rtyukmaev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_williamguerra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/albertaugustin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vikashpathak18/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevinjohndayy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vj_demien/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/colirpixoil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/goddardlewis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/laasli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jqiuss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heycamtaylor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nastya_mane/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mastermindesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ccinojasso1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nyancecom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sandywoodruff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bighanddesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sbtransparent/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aviddayentonbay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/richwild/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaysix_dizzy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tur8le/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/seyedhossein1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/privetwagner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emmandenn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dev_essentials/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jmfsocial/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_yardenoon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mateaodviteza/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/weavermedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mufaddal_mw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hafeeskhan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ashernatali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sulaqo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eddiechen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josecarlospsh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vm_f/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enricocicconi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danmartin70/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gmourier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/donjain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrxloka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_pedropinho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eitarafa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oscarowusu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ralph_lam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/panchajanyag/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/woodydotmx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jerrybai1907/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marshallchen_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xamorep/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aio___/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chaabane_wail/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/txcx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akashsharma39/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falling_soul/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sainraja/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mugukamil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johannesneu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markwienands/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karthipanraj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/balakayuriy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alan_zhang_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/layerssss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaspernordkvist/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mirfanqureshi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hanna_smi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/VMilescu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aeon56/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/m_kalibry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sreejithexp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dicesales/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhoot_amit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smenov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lonesomelemon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladimirdevic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joelcipriano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haligaliharun/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buleswapnil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/serefka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ifarafonow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vikasvinfotech/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/urrutimeoli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/areandacom/128.jpg"
];
},{}],104:[function(require,module,exports){
module["exports"] = [
"com",
"biz",
"info",
"name",
"net",
"org"
];
},{}],105:[function(require,module,exports){
module["exports"] = [
"gmail.com",
"yahoo.com",
"hotmail.com"
];
},{}],106:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.free_email = require("./free_email");
internet.domain_suffix = require("./domain_suffix");
internet.avatar_uri = require("./avatar_uri");
},{"./avatar_uri":103,"./domain_suffix":104,"./free_email":105}],107:[function(require,module,exports){
var lorem = {};
module['exports'] = lorem;
lorem.words = require("./words");
lorem.supplemental = require("./supplemental");
},{"./supplemental":108,"./words":109}],108:[function(require,module,exports){
module["exports"] = [
"abbas",
"abduco",
"abeo",
"abscido",
"absconditus",
"absens",
"absorbeo",
"absque",
"abstergo",
"absum",
"abundans",
"abutor",
"accedo",
"accendo",
"acceptus",
"accipio",
"accommodo",
"accusator",
"acer",
"acerbitas",
"acervus",
"acidus",
"acies",
"acquiro",
"acsi",
"adamo",
"adaugeo",
"addo",
"adduco",
"ademptio",
"adeo",
"adeptio",
"adfectus",
"adfero",
"adficio",
"adflicto",
"adhaero",
"adhuc",
"adicio",
"adimpleo",
"adinventitias",
"adipiscor",
"adiuvo",
"administratio",
"admiratio",
"admitto",
"admoneo",
"admoveo",
"adnuo",
"adopto",
"adsidue",
"adstringo",
"adsuesco",
"adsum",
"adulatio",
"adulescens",
"adultus",
"aduro",
"advenio",
"adversus",
"advoco",
"aedificium",
"aeger",
"aegre",
"aegrotatio",
"aegrus",
"aeneus",
"aequitas",
"aequus",
"aer",
"aestas",
"aestivus",
"aestus",
"aetas",
"aeternus",
"ager",
"aggero",
"aggredior",
"agnitio",
"agnosco",
"ago",
"ait",
"aiunt",
"alienus",
"alii",
"alioqui",
"aliqua",
"alius",
"allatus",
"alo",
"alter",
"altus",
"alveus",
"amaritudo",
"ambitus",
"ambulo",
"amicitia",
"amiculum",
"amissio",
"amita",
"amitto",
"amo",
"amor",
"amoveo",
"amplexus",
"amplitudo",
"amplus",
"ancilla",
"angelus",
"angulus",
"angustus",
"animadverto",
"animi",
"animus",
"annus",
"anser",
"ante",
"antea",
"antepono",
"antiquus",
"aperio",
"aperte",
"apostolus",
"apparatus",
"appello",
"appono",
"appositus",
"approbo",
"apto",
"aptus",
"apud",
"aqua",
"ara",
"aranea",
"arbitro",
"arbor",
"arbustum",
"arca",
"arceo",
"arcesso",
"arcus",
"argentum",
"argumentum",
"arguo",
"arma",
"armarium",
"armo",
"aro",
"ars",
"articulus",
"artificiose",
"arto",
"arx",
"ascisco",
"ascit",
"asper",
"aspicio",
"asporto",
"assentator",
"astrum",
"atavus",
"ater",
"atqui",
"atrocitas",
"atrox",
"attero",
"attollo",
"attonbitus",
"auctor",
"auctus",
"audacia",
"audax",
"audentia",
"audeo",
"audio",
"auditor",
"aufero",
"aureus",
"auris",
"aurum",
"aut",
"autem",
"autus",
"auxilium",
"avaritia",
"avarus",
"aveho",
"averto",
"avoco",
"baiulus",
"balbus",
"barba",
"bardus",
"basium",
"beatus",
"bellicus",
"bellum",
"bene",
"beneficium",
"benevolentia",
"benigne",
"bestia",
"bibo",
"bis",
"blandior",
"bonus",
"bos",
"brevis",
"cado",
"caecus",
"caelestis",
"caelum",
"calamitas",
"calcar",
"calco",
"calculus",
"callide",
"campana",
"candidus",
"canis",
"canonicus",
"canto",
"capillus",
"capio",
"capitulus",
"capto",
"caput",
"carbo",
"carcer",
"careo",
"caries",
"cariosus",
"caritas",
"carmen",
"carpo",
"carus",
"casso",
"caste",
"casus",
"catena",
"caterva",
"cattus",
"cauda",
"causa",
"caute",
"caveo",
"cavus",
"cedo",
"celebrer",
"celer",
"celo",
"cena",
"cenaculum",
"ceno",
"censura",
"centum",
"cerno",
"cernuus",
"certe",
"certo",
"certus",
"cervus",
"cetera",
"charisma",
"chirographum",
"cibo",
"cibus",
"cicuta",
"cilicium",
"cimentarius",
"ciminatio",
"cinis",
"circumvenio",
"cito",
"civis",
"civitas",
"clam",
"clamo",
"claro",
"clarus",
"claudeo",
"claustrum",
"clementia",
"clibanus",
"coadunatio",
"coaegresco",
"coepi",
"coerceo",
"cogito",
"cognatus",
"cognomen",
"cogo",
"cohaero",
"cohibeo",
"cohors",
"colligo",
"colloco",
"collum",
"colo",
"color",
"coma",
"combibo",
"comburo",
"comedo",
"comes",
"cometes",
"comis",
"comitatus",
"commemoro",
"comminor",
"commodo",
"communis",
"comparo",
"compello",
"complectus",
"compono",
"comprehendo",
"comptus",
"conatus",
"concedo",
"concido",
"conculco",
"condico",
"conduco",
"confero",
"confido",
"conforto",
"confugo",
"congregatio",
"conicio",
"coniecto",
"conitor",
"coniuratio",
"conor",
"conqueror",
"conscendo",
"conservo",
"considero",
"conspergo",
"constans",
"consuasor",
"contabesco",
"contego",
"contigo",
"contra",
"conturbo",
"conventus",
"convoco",
"copia",
"copiose",
"cornu",
"corona",
"corpus",
"correptius",
"corrigo",
"corroboro",
"corrumpo",
"coruscus",
"cotidie",
"crapula",
"cras",
"crastinus",
"creator",
"creber",
"crebro",
"credo",
"creo",
"creptio",
"crepusculum",
"cresco",
"creta",
"cribro",
"crinis",
"cruciamentum",
"crudelis",
"cruentus",
"crur",
"crustulum",
"crux",
"cubicularis",
"cubitum",
"cubo",
"cui",
"cuius",
"culpa",
"culpo",
"cultellus",
"cultura",
"cum",
"cunabula",
"cunae",
"cunctatio",
"cupiditas",
"cupio",
"cuppedia",
"cupressus",
"cur",
"cura",
"curatio",
"curia",
"curiositas",
"curis",
"curo",
"curriculum",
"currus",
"cursim",
"curso",
"cursus",
"curto",
"curtus",
"curvo",
"curvus",
"custodia",
"damnatio",
"damno",
"dapifer",
"debeo",
"debilito",
"decens",
"decerno",
"decet",
"decimus",
"decipio",
"decor",
"decretum",
"decumbo",
"dedecor",
"dedico",
"deduco",
"defaeco",
"defendo",
"defero",
"defessus",
"defetiscor",
"deficio",
"defigo",
"defleo",
"defluo",
"defungo",
"degenero",
"degero",
"degusto",
"deinde",
"delectatio",
"delego",
"deleo",
"delibero",
"delicate",
"delinquo",
"deludo",
"demens",
"demergo",
"demitto",
"demo",
"demonstro",
"demoror",
"demulceo",
"demum",
"denego",
"denique",
"dens",
"denuncio",
"denuo",
"deorsum",
"depereo",
"depono",
"depopulo",
"deporto",
"depraedor",
"deprecator",
"deprimo",
"depromo",
"depulso",
"deputo",
"derelinquo",
"derideo",
"deripio",
"desidero",
"desino",
"desipio",
"desolo",
"desparatus",
"despecto",
"despirmatio",
"infit",
"inflammatio",
"paens",
"patior",
"patria",
"patrocinor",
"patruus",
"pauci",
"paulatim",
"pauper",
"pax",
"peccatus",
"pecco",
"pecto",
"pectus",
"pecunia",
"pecus",
"peior",
"pel",
"ocer",
"socius",
"sodalitas",
"sol",
"soleo",
"solio",
"solitudo",
"solium",
"sollers",
"sollicito",
"solum",
"solus",
"solutio",
"solvo",
"somniculosus",
"somnus",
"sonitus",
"sono",
"sophismata",
"sopor",
"sordeo",
"sortitus",
"spargo",
"speciosus",
"spectaculum",
"speculum",
"sperno",
"spero",
"spes",
"spiculum",
"spiritus",
"spoliatio",
"sponte",
"stabilis",
"statim",
"statua",
"stella",
"stillicidium",
"stipes",
"stips",
"sto",
"strenuus",
"strues",
"studio",
"stultus",
"suadeo",
"suasoria",
"sub",
"subito",
"subiungo",
"sublime",
"subnecto",
"subseco",
"substantia",
"subvenio",
"succedo",
"succurro",
"sufficio",
"suffoco",
"suffragium",
"suggero",
"sui",
"sulum",
"sum",
"summa",
"summisse",
"summopere",
"sumo",
"sumptus",
"supellex",
"super",
"suppellex",
"supplanto",
"suppono",
"supra",
"surculus",
"surgo",
"sursum",
"suscipio",
"suspendo",
"sustineo",
"suus",
"synagoga",
"tabella",
"tabernus",
"tabesco",
"tabgo",
"tabula",
"taceo",
"tactus",
"taedium",
"talio",
"talis",
"talus",
"tam",
"tamdiu",
"tamen",
"tametsi",
"tamisium",
"tamquam",
"tandem",
"tantillus",
"tantum",
"tardus",
"tego",
"temeritas",
"temperantia",
"templum",
"temptatio",
"tempus",
"tenax",
"tendo",
"teneo",
"tener",
"tenuis",
"tenus",
"tepesco",
"tepidus",
"ter",
"terebro",
"teres",
"terga",
"tergeo",
"tergiversatio",
"tergo",
"tergum",
"termes",
"terminatio",
"tero",
"terra",
"terreo",
"territo",
"terror",
"tersus",
"tertius",
"testimonium",
"texo",
"textilis",
"textor",
"textus",
"thalassinus",
"theatrum",
"theca",
"thema",
"theologus",
"thermae",
"thesaurus",
"thesis",
"thorax",
"thymbra",
"thymum",
"tibi",
"timidus",
"timor",
"titulus",
"tolero",
"tollo",
"tondeo",
"tonsor",
"torqueo",
"torrens",
"tot",
"totidem",
"toties",
"totus",
"tracto",
"trado",
"traho",
"trans",
"tredecim",
"tremo",
"trepide",
"tres",
"tribuo",
"tricesimus",
"triduana",
"triginta",
"tripudio",
"tristis",
"triumphus",
"trucido",
"truculenter",
"tubineus",
"tui",
"tum",
"tumultus",
"tunc",
"turba",
"turbo",
"turpe",
"turpis",
"tutamen",
"tutis",
"tyrannus",
"uberrime",
"ubi",
"ulciscor",
"ullus",
"ulterius",
"ultio",
"ultra",
"umbra",
"umerus",
"umquam",
"una",
"unde",
"undique",
"universe",
"unus",
"urbanus",
"urbs",
"uredo",
"usitas",
"usque",
"ustilo",
"ustulo",
"usus",
"uter",
"uterque",
"utilis",
"utique",
"utor",
"utpote",
"utrimque",
"utroque",
"utrum",
"uxor",
"vaco",
"vacuus",
"vado",
"vae",
"valde",
"valens",
"valeo",
"valetudo",
"validus",
"vallum",
"vapulus",
"varietas",
"varius",
"vehemens",
"vel",
"velociter",
"velum",
"velut",
"venia",
"venio",
"ventito",
"ventosus",
"ventus",
"venustas",
"ver",
"verbera",
"verbum",
"vere",
"verecundia",
"vereor",
"vergo",
"veritas",
"vero",
"versus",
"verto",
"verumtamen",
"verus",
"vesco",
"vesica",
"vesper",
"vespillo",
"vester",
"vestigium",
"vestrum",
"vetus",
"via",
"vicinus",
"vicissitudo",
"victoria",
"victus",
"videlicet",
"video",
"viduata",
"viduo",
"vigilo",
"vigor",
"vilicus",
"vilis",
"vilitas",
"villa",
"vinco",
"vinculum",
"vindico",
"vinitor",
"vinum",
"vir",
"virga",
"virgo",
"viridis",
"viriliter",
"virtus",
"vis",
"viscus",
"vita",
"vitiosus",
"vitium",
"vito",
"vivo",
"vix",
"vobis",
"vociferor",
"voco",
"volaticus",
"volo",
"volubilis",
"voluntarius",
"volup",
"volutabrum",
"volva",
"vomer",
"vomica",
"vomito",
"vorago",
"vorax",
"voro",
"vos",
"votum",
"voveo",
"vox",
"vulariter",
"vulgaris",
"vulgivagus",
"vulgo",
"vulgus",
"vulnero",
"vulnus",
"vulpes",
"vulticulus",
"vultuosus",
"xiphias"
];
},{}],109:[function(require,module,exports){
module["exports"] = [
"alias",
"consequatur",
"aut",
"perferendis",
"sit",
"voluptatem",
"accusantium",
"doloremque",
"aperiam",
"eaque",
"ipsa",
"quae",
"ab",
"illo",
"inventore",
"veritatis",
"et",
"quasi",
"architecto",
"beatae",
"vitae",
"dicta",
"sunt",
"explicabo",
"aspernatur",
"aut",
"odit",
"aut",
"fugit",
"sed",
"quia",
"consequuntur",
"magni",
"dolores",
"eos",
"qui",
"ratione",
"voluptatem",
"sequi",
"nesciunt",
"neque",
"dolorem",
"ipsum",
"quia",
"dolor",
"sit",
"amet",
"consectetur",
"adipisci",
"velit",
"sed",
"quia",
"non",
"numquam",
"eius",
"modi",
"tempora",
"incidunt",
"ut",
"labore",
"et",
"dolore",
"magnam",
"aliquam",
"quaerat",
"voluptatem",
"ut",
"enim",
"ad",
"minima",
"veniam",
"quis",
"nostrum",
"exercitationem",
"ullam",
"corporis",
"nemo",
"enim",
"ipsam",
"voluptatem",
"quia",
"voluptas",
"sit",
"suscipit",
"laboriosam",
"nisi",
"ut",
"aliquid",
"ex",
"ea",
"commodi",
"consequatur",
"quis",
"autem",
"vel",
"eum",
"iure",
"reprehenderit",
"qui",
"in",
"ea",
"voluptate",
"velit",
"esse",
"quam",
"nihil",
"molestiae",
"et",
"iusto",
"odio",
"dignissimos",
"ducimus",
"qui",
"blanditiis",
"praesentium",
"laudantium",
"totam",
"rem",
"voluptatum",
"deleniti",
"atque",
"corrupti",
"quos",
"dolores",
"et",
"quas",
"molestias",
"excepturi",
"sint",
"occaecati",
"cupiditate",
"non",
"provident",
"sed",
"ut",
"perspiciatis",
"unde",
"omnis",
"iste",
"natus",
"error",
"similique",
"sunt",
"in",
"culpa",
"qui",
"officia",
"deserunt",
"mollitia",
"animi",
"id",
"est",
"laborum",
"et",
"dolorum",
"fuga",
"et",
"harum",
"quidem",
"rerum",
"facilis",
"est",
"et",
"expedita",
"distinctio",
"nam",
"libero",
"tempore",
"cum",
"soluta",
"nobis",
"est",
"eligendi",
"optio",
"cumque",
"nihil",
"impedit",
"quo",
"porro",
"quisquam",
"est",
"qui",
"minus",
"id",
"quod",
"maxime",
"placeat",
"facere",
"possimus",
"omnis",
"voluptas",
"assumenda",
"est",
"omnis",
"dolor",
"repellendus",
"temporibus",
"autem",
"quibusdam",
"et",
"aut",
"consequatur",
"vel",
"illum",
"qui",
"dolorem",
"eum",
"fugiat",
"quo",
"voluptas",
"nulla",
"pariatur",
"at",
"vero",
"eos",
"et",
"accusamus",
"officiis",
"debitis",
"aut",
"rerum",
"necessitatibus",
"saepe",
"eveniet",
"ut",
"et",
"voluptates",
"repudiandae",
"sint",
"et",
"molestiae",
"non",
"recusandae",
"itaque",
"earum",
"rerum",
"hic",
"tenetur",
"a",
"sapiente",
"delectus",
"ut",
"aut",
"reiciendis",
"voluptatibus",
"maiores",
"doloribus",
"asperiores",
"repellat"
];
},{}],110:[function(require,module,exports){
module["exports"] = [
"Aaliyah",
"Aaron",
"Abagail",
"Abbey",
"Abbie",
"Abbigail",
"Abby",
"Abdiel",
"Abdul",
"Abdullah",
"Abe",
"Abel",
"Abelardo",
"Abigail",
"Abigale",
"Abigayle",
"Abner",
"Abraham",
"Ada",
"Adah",
"Adalberto",
"Adaline",
"Adam",
"Adan",
"Addie",
"Addison",
"Adela",
"Adelbert",
"Adele",
"Adelia",
"Adeline",
"Adell",
"Adella",
"Adelle",
"Aditya",
"Adolf",
"Adolfo",
"Adolph",
"Adolphus",
"Adonis",
"Adrain",
"Adrian",
"Adriana",
"Adrianna",
"Adriel",
"Adrien",
"Adrienne",
"Afton",
"Aglae",
"Agnes",
"Agustin",
"Agustina",
"Ahmad",
"Ahmed",
"Aida",
"Aidan",
"Aiden",
"Aileen",
"Aimee",
"Aisha",
"Aiyana",
"Akeem",
"Al",
"Alaina",
"Alan",
"Alana",
"Alanis",
"Alanna",
"Alayna",
"Alba",
"Albert",
"Alberta",
"Albertha",
"Alberto",
"Albin",
"Albina",
"Alda",
"Alden",
"Alec",
"Aleen",
"Alejandra",
"Alejandrin",
"Alek",
"Alena",
"Alene",
"Alessandra",
"Alessandro",
"Alessia",
"Aletha",
"Alex",
"Alexa",
"Alexander",
"Alexandra",
"Alexandre",
"Alexandrea",
"Alexandria",
"Alexandrine",
"Alexandro",
"Alexane",
"Alexanne",
"Alexie",
"Alexis",
"Alexys",
"Alexzander",
"Alf",
"Alfonso",
"Alfonzo",
"Alford",
"Alfred",
"Alfreda",
"Alfredo",
"Ali",
"Alia",
"Alice",
"Alicia",
"Alisa",
"Alisha",
"Alison",
"Alivia",
"Aliya",
"Aliyah",
"Aliza",
"Alize",
"Allan",
"Allen",
"Allene",
"Allie",
"Allison",
"Ally",
"Alphonso",
"Alta",
"Althea",
"Alva",
"Alvah",
"Alvena",
"Alvera",
"Alverta",
"Alvina",
"Alvis",
"Alyce",
"Alycia",
"Alysa",
"Alysha",
"Alyson",
"Alysson",
"Amalia",
"Amanda",
"Amani",
"Amara",
"Amari",
"Amaya",
"Amber",
"Ambrose",
"Amelia",
"Amelie",
"Amely",
"America",
"Americo",
"Amie",
"Amina",
"Amir",
"Amira",
"Amiya",
"Amos",
"Amparo",
"Amy",
"Amya",
"Ana",
"Anabel",
"Anabelle",
"Anahi",
"Anais",
"Anastacio",
"Anastasia",
"Anderson",
"Andre",
"Andreane",
"Andreanne",
"Andres",
"Andrew",
"Andy",
"Angel",
"Angela",
"Angelica",
"Angelina",
"Angeline",
"Angelita",
"Angelo",
"Angie",
"Angus",
"Anibal",
"Anika",
"Anissa",
"Anita",
"Aniya",
"Aniyah",
"Anjali",
"Anna",
"Annabel",
"Annabell",
"Annabelle",
"Annalise",
"Annamae",
"Annamarie",
"Anne",
"Annetta",
"Annette",
"Annie",
"Ansel",
"Ansley",
"Anthony",
"Antoinette",
"Antone",
"Antonetta",
"Antonette",
"Antonia",
"Antonietta",
"Antonina",
"Antonio",
"Antwan",
"Antwon",
"Anya",
"April",
"Ara",
"Araceli",
"Aracely",
"Arch",
"Archibald",
"Ardella",
"Arden",
"Ardith",
"Arely",
"Ari",
"Ariane",
"Arianna",
"Aric",
"Ariel",
"Arielle",
"Arjun",
"Arlene",
"Arlie",
"Arlo",
"Armand",
"Armando",
"Armani",
"Arnaldo",
"Arne",
"Arno",
"Arnold",
"Arnoldo",
"Arnulfo",
"Aron",
"Art",
"Arthur",
"Arturo",
"Arvel",
"Arvid",
"Arvilla",
"Aryanna",
"Asa",
"Asha",
"Ashlee",
"Ashleigh",
"Ashley",
"Ashly",
"Ashlynn",
"Ashton",
"Ashtyn",
"Asia",
"Assunta",
"Astrid",
"Athena",
"Aubree",
"Aubrey",
"Audie",
"Audra",
"Audreanne",
"Audrey",
"August",
"Augusta",
"Augustine",
"Augustus",
"Aurelia",
"Aurelie",
"Aurelio",
"Aurore",
"Austen",
"Austin",
"Austyn",
"Autumn",
"Ava",
"Avery",
"Avis",
"Axel",
"Ayana",
"Ayden",
"Ayla",
"Aylin",
"Baby",
"Bailee",
"Bailey",
"Barbara",
"Barney",
"Baron",
"Barrett",
"Barry",
"Bart",
"Bartholome",
"Barton",
"Baylee",
"Beatrice",
"Beau",
"Beaulah",
"Bell",
"Bella",
"Belle",
"Ben",
"Benedict",
"Benjamin",
"Bennett",
"Bennie",
"Benny",
"Benton",
"Berenice",
"Bernadette",
"Bernadine",
"Bernard",
"Bernardo",
"Berneice",
"Bernhard",
"Bernice",
"Bernie",
"Berniece",
"Bernita",
"Berry",
"Bert",
"Berta",
"Bertha",
"Bertram",
"Bertrand",
"Beryl",
"Bessie",
"Beth",
"Bethany",
"Bethel",
"Betsy",
"Bette",
"Bettie",
"Betty",
"Bettye",
"Beulah",
"Beverly",
"Bianka",
"Bill",
"Billie",
"Billy",
"Birdie",
"Blair",
"Blaise",
"Blake",
"Blanca",
"Blanche",
"Blaze",
"Bo",
"Bobbie",
"Bobby",
"Bonita",
"Bonnie",
"Boris",
"Boyd",
"Brad",
"Braden",
"Bradford",
"Bradley",
"Bradly",
"Brady",
"Braeden",
"Brain",
"Brandi",
"Brando",
"Brandon",
"Brandt",
"Brandy",
"Brandyn",
"Brannon",
"Branson",
"Brant",
"Braulio",
"Braxton",
"Brayan",
"Breana",
"Breanna",
"Breanne",
"Brenda",
"Brendan",
"Brenden",
"Brendon",
"Brenna",
"Brennan",
"Brennon",
"Brent",
"Bret",
"Brett",
"Bria",
"Brian",
"Briana",
"Brianne",
"Brice",
"Bridget",
"Bridgette",
"Bridie",
"Brielle",
"Brigitte",
"Brionna",
"Brisa",
"Britney",
"Brittany",
"Brock",
"Broderick",
"Brody",
"Brook",
"Brooke",
"Brooklyn",
"Brooks",
"Brown",
"Bruce",
"Bryana",
"Bryce",
"Brycen",
"Bryon",
"Buck",
"Bud",
"Buddy",
"Buford",
"Bulah",
"Burdette",
"Burley",
"Burnice",
"Buster",
"Cade",
"Caden",
"Caesar",
"Caitlyn",
"Cale",
"Caleb",
"Caleigh",
"Cali",
"Calista",
"Callie",
"Camden",
"Cameron",
"Camila",
"Camilla",
"Camille",
"Camren",
"Camron",
"Camryn",
"Camylle",
"Candace",
"Candelario",
"Candice",
"Candida",
"Candido",
"Cara",
"Carey",
"Carissa",
"Carlee",
"Carleton",
"Carley",
"Carli",
"Carlie",
"Carlo",
"Carlos",
"Carlotta",
"Carmel",
"Carmela",
"Carmella",
"Carmelo",
"Carmen",
"Carmine",
"Carol",
"Carolanne",
"Carole",
"Carolina",
"Caroline",
"Carolyn",
"Carolyne",
"Carrie",
"Carroll",
"Carson",
"Carter",
"Cary",
"Casandra",
"Casey",
"Casimer",
"Casimir",
"Casper",
"Cassandra",
"Cassandre",
"Cassidy",
"Cassie",
"Catalina",
"Caterina",
"Catharine",
"Catherine",
"Cathrine",
"Cathryn",
"Cathy",
"Cayla",
"Ceasar",
"Cecelia",
"Cecil",
"Cecile",
"Cecilia",
"Cedrick",
"Celestine",
"Celestino",
"Celia",
"Celine",
"Cesar",
"Chad",
"Chadd",
"Chadrick",
"Chaim",
"Chance",
"Chandler",
"Chanel",
"Chanelle",
"Charity",
"Charlene",
"Charles",
"Charley",
"Charlie",
"Charlotte",
"Chase",
"Chasity",
"Chauncey",
"Chaya",
"Chaz",
"Chelsea",
"Chelsey",
"Chelsie",
"Chesley",
"Chester",
"Chet",
"Cheyanne",
"Cheyenne",
"Chloe",
"Chris",
"Christ",
"Christa",
"Christelle",
"Christian",
"Christiana",
"Christina",
"Christine",
"Christop",
"Christophe",
"Christopher",
"Christy",
"Chyna",
"Ciara",
"Cicero",
"Cielo",
"Cierra",
"Cindy",
"Citlalli",
"Clair",
"Claire",
"Clara",
"Clarabelle",
"Clare",
"Clarissa",
"Clark",
"Claud",
"Claude",
"Claudia",
"Claudie",
"Claudine",
"Clay",
"Clemens",
"Clement",
"Clementina",
"Clementine",
"Clemmie",
"Cleo",
"Cleora",
"Cleta",
"Cletus",
"Cleve",
"Cleveland",
"Clifford",
"Clifton",
"Clint",
"Clinton",
"Clotilde",
"Clovis",
"Cloyd",
"Clyde",
"Coby",
"Cody",
"Colby",
"Cole",
"Coleman",
"Colin",
"Colleen",
"Collin",
"Colt",
"Colten",
"Colton",
"Columbus",
"Concepcion",
"Conner",
"Connie",
"Connor",
"Conor",
"Conrad",
"Constance",
"Constantin",
"Consuelo",
"Cooper",
"Cora",
"Coralie",
"Corbin",
"Cordelia",
"Cordell",
"Cordia",
"Cordie",
"Corene",
"Corine",
"Cornelius",
"Cornell",
"Corrine",
"Cortez",
"Cortney",
"Cory",
"Coty",
"Courtney",
"Coy",
"Craig",
"Crawford",
"Creola",
"Cristal",
"Cristian",
"Cristina",
"Cristobal",
"Cristopher",
"Cruz",
"Crystal",
"Crystel",
"Cullen",
"Curt",
"Curtis",
"Cydney",
"Cynthia",
"Cyril",
"Cyrus",
"Dagmar",
"Dahlia",
"Daija",
"Daisha",
"Daisy",
"Dakota",
"Dale",
"Dallas",
"Dallin",
"Dalton",
"Damaris",
"Dameon",
"Damian",
"Damien",
"Damion",
"Damon",
"Dan",
"Dana",
"Dandre",
"Dane",
"D'angelo",
"Dangelo",
"Danial",
"Daniela",
"Daniella",
"Danielle",
"Danika",
"Dannie",
"Danny",
"Dante",
"Danyka",
"Daphne",
"Daphnee",
"Daphney",
"Darby",
"Daren",
"Darian",
"Dariana",
"Darien",
"Dario",
"Darion",
"Darius",
"Darlene",
"Daron",
"Darrel",
"Darrell",
"Darren",
"Darrick",
"Darrin",
"Darrion",
"Darron",
"Darryl",
"Darwin",
"Daryl",
"Dashawn",
"Dasia",
"Dave",
"David",
"Davin",
"Davion",
"Davon",
"Davonte",
"Dawn",
"Dawson",
"Dax",
"Dayana",
"Dayna",
"Dayne",
"Dayton",
"Dean",
"Deangelo",
"Deanna",
"Deborah",
"Declan",
"Dedric",
"Dedrick",
"Dee",
"Deion",
"Deja",
"Dejah",
"Dejon",
"Dejuan",
"Delaney",
"Delbert",
"Delfina",
"Delia",
"Delilah",
"Dell",
"Della",
"Delmer",
"Delores",
"Delpha",
"Delphia",
"Delphine",
"Delta",
"Demarco",
"Demarcus",
"Demario",
"Demetris",
"Demetrius",
"Demond",
"Dena",
"Denis",
"Dennis",
"Deon",
"Deondre",
"Deontae",
"Deonte",
"Dereck",
"Derek",
"Derick",
"Deron",
"Derrick",
"Deshaun",
"Deshawn",
"Desiree",
"Desmond",
"Dessie",
"Destany",
"Destin",
"Destinee",
"Destiney",
"Destini",
"Destiny",
"Devan",
"Devante",
"Deven",
"Devin",
"Devon",
"Devonte",
"Devyn",
"Dewayne",
"Dewitt",
"Dexter",
"Diamond",
"Diana",
"Dianna",
"Diego",
"Dillan",
"Dillon",
"Dimitri",
"Dina",
"Dino",
"Dion",
"Dixie",
"Dock",
"Dolly",
"Dolores",
"Domenic",
"Domenica",
"Domenick",
"Domenico",
"Domingo",
"Dominic",
"Dominique",
"Don",
"Donald",
"Donato",
"Donavon",
"Donna",
"Donnell",
"Donnie",
"Donny",
"Dora",
"Dorcas",
"Dorian",
"Doris",
"Dorothea",
"Dorothy",
"Dorris",
"Dortha",
"Dorthy",
"Doug",
"Douglas",
"Dovie",
"Doyle",
"Drake",
"Drew",
"Duane",
"Dudley",
"Dulce",
"Duncan",
"Durward",
"Dustin",
"Dusty",
"Dwight",
"Dylan",
"Earl",
"Earlene",
"Earline",
"Earnest",
"Earnestine",
"Easter",
"Easton",
"Ebba",
"Ebony",
"Ed",
"Eda",
"Edd",
"Eddie",
"Eden",
"Edgar",
"Edgardo",
"Edison",
"Edmond",
"Edmund",
"Edna",
"Eduardo",
"Edward",
"Edwardo",
"Edwin",
"Edwina",
"Edyth",
"Edythe",
"Effie",
"Efrain",
"Efren",
"Eileen",
"Einar",
"Eino",
"Eladio",
"Elaina",
"Elbert",
"Elda",
"Eldon",
"Eldora",
"Eldred",
"Eldridge",
"Eleanora",
"Eleanore",
"Eleazar",
"Electa",
"Elena",
"Elenor",
"Elenora",
"Eleonore",
"Elfrieda",
"Eli",
"Elian",
"Eliane",
"Elias",
"Eliezer",
"Elijah",
"Elinor",
"Elinore",
"Elisa",
"Elisabeth",
"Elise",
"Eliseo",
"Elisha",
"Elissa",
"Eliza",
"Elizabeth",
"Ella",
"Ellen",
"Ellie",
"Elliot",
"Elliott",
"Ellis",
"Ellsworth",
"Elmer",
"Elmira",
"Elmo",
"Elmore",
"Elna",
"Elnora",
"Elody",
"Eloisa",
"Eloise",
"Elouise",
"Eloy",
"Elroy",
"Elsa",
"Else",
"Elsie",
"Elta",
"Elton",
"Elva",
"Elvera",
"Elvie",
"Elvis",
"Elwin",
"Elwyn",
"Elyse",
"Elyssa",
"Elza",
"Emanuel",
"Emelia",
"Emelie",
"Emely",
"Emerald",
"Emerson",
"Emery",
"Emie",
"Emil",
"Emile",
"Emilia",
"Emiliano",
"Emilie",
"Emilio",
"Emily",
"Emma",
"Emmalee",
"Emmanuel",
"Emmanuelle",
"Emmet",
"Emmett",
"Emmie",
"Emmitt",
"Emmy",
"Emory",
"Ena",
"Enid",
"Enoch",
"Enola",
"Enos",
"Enrico",
"Enrique",
"Ephraim",
"Era",
"Eriberto",
"Eric",
"Erica",
"Erich",
"Erick",
"Ericka",
"Erik",
"Erika",
"Erin",
"Erling",
"Erna",
"Ernest",
"Ernestina",
"Ernestine",
"Ernesto",
"Ernie",
"Ervin",
"Erwin",
"Eryn",
"Esmeralda",
"Esperanza",
"Esta",
"Esteban",
"Estefania",
"Estel",
"Estell",
"Estella",
"Estelle",
"Estevan",
"Esther",
"Estrella",
"Etha",
"Ethan",
"Ethel",
"Ethelyn",
"Ethyl",
"Ettie",
"Eudora",
"Eugene",
"Eugenia",
"Eula",
"Eulah",
"Eulalia",
"Euna",
"Eunice",
"Eusebio",
"Eva",
"Evalyn",
"Evan",
"Evangeline",
"Evans",
"Eve",
"Eveline",
"Evelyn",
"Everardo",
"Everett",
"Everette",
"Evert",
"Evie",
"Ewald",
"Ewell",
"Ezekiel",
"Ezequiel",
"Ezra",
"Fabian",
"Fabiola",
"Fae",
"Fannie",
"Fanny",
"Fatima",
"Faustino",
"Fausto",
"Favian",
"Fay",
"Faye",
"Federico",
"Felicia",
"Felicita",
"Felicity",
"Felipa",
"Felipe",
"Felix",
"Felton",
"Fermin",
"Fern",
"Fernando",
"Ferne",
"Fidel",
"Filiberto",
"Filomena",
"Finn",
"Fiona",
"Flavie",
"Flavio",
"Fleta",
"Fletcher",
"Flo",
"Florence",
"Florencio",
"Florian",
"Florida",
"Florine",
"Flossie",
"Floy",
"Floyd",
"Ford",
"Forest",
"Forrest",
"Foster",
"Frances",
"Francesca",
"Francesco",
"Francis",
"Francisca",
"Francisco",
"Franco",
"Frank",
"Frankie",
"Franz",
"Fred",
"Freda",
"Freddie",
"Freddy",
"Frederic",
"Frederick",
"Frederik",
"Frederique",
"Fredrick",
"Fredy",
"Freeda",
"Freeman",
"Freida",
"Frida",
"Frieda",
"Friedrich",
"Fritz",
"Furman",
"Gabe",
"Gabriel",
"Gabriella",
"Gabrielle",
"Gaetano",
"Gage",
"Gail",
"Gardner",
"Garett",
"Garfield",
"Garland",
"Garnet",
"Garnett",
"Garret",
"Garrett",
"Garrick",
"Garrison",
"Garry",
"Garth",
"Gaston",
"Gavin",
"Gay",
"Gayle",
"Gaylord",
"Gene",
"General",
"Genesis",
"Genevieve",
"Gennaro",
"Genoveva",
"Geo",
"Geoffrey",
"George",
"Georgette",
"Georgiana",
"Georgianna",
"Geovanni",
"Geovanny",
"Geovany",
"Gerald",
"Geraldine",
"Gerard",
"Gerardo",
"Gerda",
"Gerhard",
"Germaine",
"German",
"Gerry",
"Gerson",
"Gertrude",
"Gia",
"Gianni",
"Gideon",
"Gilbert",
"Gilberto",
"Gilda",
"Giles",
"Gillian",
"Gina",
"Gino",
"Giovani",
"Giovanna",
"Giovanni",
"Giovanny",
"Gisselle",
"Giuseppe",
"Gladyce",
"Gladys",
"Glen",
"Glenda",
"Glenna",
"Glennie",
"Gloria",
"Godfrey",
"Golda",
"Golden",
"Gonzalo",
"Gordon",
"Grace",
"Gracie",
"Graciela",
"Grady",
"Graham",
"Grant",
"Granville",
"Grayce",
"Grayson",
"Green",
"Greg",
"Gregg",
"Gregoria",
"Gregorio",
"Gregory",
"Greta",
"Gretchen",
"Greyson",
"Griffin",
"Grover",
"Guadalupe",
"Gudrun",
"Guido",
"Guillermo",
"Guiseppe",
"Gunnar",
"Gunner",
"Gus",
"Gussie",
"Gust",
"Gustave",
"Guy",
"Gwen",
"Gwendolyn",
"Hadley",
"Hailee",
"Hailey",
"Hailie",
"Hal",
"Haleigh",
"Haley",
"Halie",
"Halle",
"Hallie",
"Hank",
"Hanna",
"Hannah",
"Hans",
"Hardy",
"Harley",
"Harmon",
"Harmony",
"Harold",
"Harrison",
"Harry",
"Harvey",
"Haskell",
"Hassan",
"Hassie",
"Hattie",
"Haven",
"Hayden",
"Haylee",
"Hayley",
"Haylie",
"Hazel",
"Hazle",
"Heath",
"Heather",
"Heaven",
"Heber",
"Hector",
"Heidi",
"Helen",
"Helena",
"Helene",
"Helga",
"Hellen",
"Helmer",
"Heloise",
"Henderson",
"Henri",
"Henriette",
"Henry",
"Herbert",
"Herman",
"Hermann",
"Hermina",
"Herminia",
"Herminio",
"Hershel",
"Herta",
"Hertha",
"Hester",
"Hettie",
"Hilario",
"Hilbert",
"Hilda",
"Hildegard",
"Hillard",
"Hillary",
"Hilma",
"Hilton",
"Hipolito",
"Hiram",
"Hobart",
"Holden",
"Hollie",
"Hollis",
"Holly",
"Hope",
"Horace",
"Horacio",
"Hortense",
"Hosea",
"Houston",
"Howard",
"Howell",
"Hoyt",
"Hubert",
"Hudson",
"Hugh",
"Hulda",
"Humberto",
"Hunter",
"Hyman",
"Ian",
"Ibrahim",
"Icie",
"Ida",
"Idell",
"Idella",
"Ignacio",
"Ignatius",
"Ike",
"Ila",
"Ilene",
"Iliana",
"Ima",
"Imani",
"Imelda",
"Immanuel",
"Imogene",
"Ines",
"Irma",
"Irving",
"Irwin",
"Isaac",
"Isabel",
"Isabell",
"Isabella",
"Isabelle",
"Isac",
"Isadore",
"Isai",
"Isaiah",
"Isaias",
"Isidro",
"Ismael",
"Isobel",
"Isom",
"Israel",
"Issac",
"Itzel",
"Iva",
"Ivah",
"Ivory",
"Ivy",
"Izabella",
"Izaiah",
"Jabari",
"Jace",
"Jacey",
"Jacinthe",
"Jacinto",
"Jack",
"Jackeline",
"Jackie",
"Jacklyn",
"Jackson",
"Jacky",
"Jaclyn",
"Jacquelyn",
"Jacques",
"Jacynthe",
"Jada",
"Jade",
"Jaden",
"Jadon",
"Jadyn",
"Jaeden",
"Jaida",
"Jaiden",
"Jailyn",
"Jaime",
"Jairo",
"Jakayla",
"Jake",
"Jakob",
"Jaleel",
"Jalen",
"Jalon",
"Jalyn",
"Jamaal",
"Jamal",
"Jamar",
"Jamarcus",
"Jamel",
"Jameson",
"Jamey",
"Jamie",
"Jamil",
"Jamir",
"Jamison",
"Jammie",
"Jan",
"Jana",
"Janae",
"Jane",
"Janelle",
"Janessa",
"Janet",
"Janice",
"Janick",
"Janie",
"Janis",
"Janiya",
"Jannie",
"Jany",
"Jaquan",
"Jaquelin",
"Jaqueline",
"Jared",
"Jaren",
"Jarod",
"Jaron",
"Jarred",
"Jarrell",
"Jarret",
"Jarrett",
"Jarrod",
"Jarvis",
"Jasen",
"Jasmin",
"Jason",
"Jasper",
"Jaunita",
"Javier",
"Javon",
"Javonte",
"Jay",
"Jayce",
"Jaycee",
"Jayda",
"Jayde",
"Jayden",
"Jaydon",
"Jaylan",
"Jaylen",
"Jaylin",
"Jaylon",
"Jayme",
"Jayne",
"Jayson",
"Jazlyn",
"Jazmin",
"Jazmyn",
"Jazmyne",
"Jean",
"Jeanette",
"Jeanie",
"Jeanne",
"Jed",
"Jedediah",
"Jedidiah",
"Jeff",
"Jefferey",
"Jeffery",
"Jeffrey",
"Jeffry",
"Jena",
"Jenifer",
"Jennie",
"Jennifer",
"Jennings",
"Jennyfer",
"Jensen",
"Jerad",
"Jerald",
"Jeramie",
"Jeramy",
"Jerel",
"Jeremie",
"Jeremy",
"Jermain",
"Jermaine",
"Jermey",
"Jerod",
"Jerome",
"Jeromy",
"Jerrell",
"Jerrod",
"Jerrold",
"Jerry",
"Jess",
"Jesse",
"Jessica",
"Jessie",
"Jessika",
"Jessy",
"Jessyca",
"Jesus",
"Jett",
"Jettie",
"Jevon",
"Jewel",
"Jewell",
"Jillian",
"Jimmie",
"Jimmy",
"Jo",
"Joan",
"Joana",
"Joanie",
"Joanne",
"Joannie",
"Joanny",
"Joany",
"Joaquin",
"Jocelyn",
"Jodie",
"Jody",
"Joe",
"Joel",
"Joelle",
"Joesph",
"Joey",
"Johan",
"Johann",
"Johanna",
"Johathan",
"John",
"Johnathan",
"Johnathon",
"Johnnie",
"Johnny",
"Johnpaul",
"Johnson",
"Jolie",
"Jon",
"Jonas",
"Jonatan",
"Jonathan",
"Jonathon",
"Jordan",
"Jordane",
"Jordi",
"Jordon",
"Jordy",
"Jordyn",
"Jorge",
"Jose",
"Josefa",
"Josefina",
"Joseph",
"Josephine",
"Josh",
"Joshua",
"Joshuah",
"Josiah",
"Josiane",
"Josianne",
"Josie",
"Josue",
"Jovan",
"Jovani",
"Jovanny",
"Jovany",
"Joy",
"Joyce",
"Juana",
"Juanita",
"Judah",
"Judd",
"Jude",
"Judge",
"Judson",
"Judy",
"Jules",
"Julia",
"Julian",
"Juliana",
"Julianne",
"Julie",
"Julien",
"Juliet",
"Julio",
"Julius",
"June",
"Junior",
"Junius",
"Justen",
"Justice",
"Justina",
"Justine",
"Juston",
"Justus",
"Justyn",
"Juvenal",
"Juwan",
"Kacey",
"Kaci",
"Kacie",
"Kade",
"Kaden",
"Kadin",
"Kaela",
"Kaelyn",
"Kaia",
"Kailee",
"Kailey",
"Kailyn",
"Kaitlin",
"Kaitlyn",
"Kale",
"Kaleb",
"Kaleigh",
"Kaley",
"Kali",
"Kallie",
"Kameron",
"Kamille",
"Kamren",
"Kamron",
"Kamryn",
"Kane",
"Kara",
"Kareem",
"Karelle",
"Karen",
"Kari",
"Kariane",
"Karianne",
"Karina",
"Karine",
"Karl",
"Karlee",
"Karley",
"Karli",
"Karlie",
"Karolann",
"Karson",
"Kasandra",
"Kasey",
"Kassandra",
"Katarina",
"Katelin",
"Katelyn",
"Katelynn",
"Katharina",
"Katherine",
"Katheryn",
"Kathleen",
"Kathlyn",
"Kathryn",
"Kathryne",
"Katlyn",
"Katlynn",
"Katrina",
"Katrine",
"Kattie",
"Kavon",
"Kay",
"Kaya",
"Kaycee",
"Kayden",
"Kayla",
"Kaylah",
"Kaylee",
"Kayleigh",
"Kayley",
"Kayli",
"Kaylie",
"Kaylin",
"Keagan",
"Keanu",
"Keara",
"Keaton",
"Keegan",
"Keeley",
"Keely",
"Keenan",
"Keira",
"Keith",
"Kellen",
"Kelley",
"Kelli",
"Kellie",
"Kelly",
"Kelsi",
"Kelsie",
"Kelton",
"Kelvin",
"Ken",
"Kendall",
"Kendra",
"Kendrick",
"Kenna",
"Kennedi",
"Kennedy",
"Kenneth",
"Kennith",
"Kenny",
"Kenton",
"Kenya",
"Kenyatta",
"Kenyon",
"Keon",
"Keshaun",
"Keshawn",
"Keven",
"Kevin",
"Kevon",
"Keyon",
"Keyshawn",
"Khalid",
"Khalil",
"Kian",
"Kiana",
"Kianna",
"Kiara",
"Kiarra",
"Kiel",
"Kiera",
"Kieran",
"Kiley",
"Kim",
"Kimberly",
"King",
"Kip",
"Kira",
"Kirk",
"Kirsten",
"Kirstin",
"Kitty",
"Kobe",
"Koby",
"Kody",
"Kolby",
"Kole",
"Korbin",
"Korey",
"Kory",
"Kraig",
"Kris",
"Krista",
"Kristian",
"Kristin",
"Kristina",
"Kristofer",
"Kristoffer",
"Kristopher",
"Kristy",
"Krystal",
"Krystel",
"Krystina",
"Kurt",
"Kurtis",
"Kyla",
"Kyle",
"Kylee",
"Kyleigh",
"Kyler",
"Kylie",
"Kyra",
"Lacey",
"Lacy",
"Ladarius",
"Lafayette",
"Laila",
"Laisha",
"Lamar",
"Lambert",
"Lamont",
"Lance",
"Landen",
"Lane",
"Laney",
"Larissa",
"Laron",
"Larry",
"Larue",
"Laura",
"Laurel",
"Lauren",
"Laurence",
"Lauretta",
"Lauriane",
"Laurianne",
"Laurie",
"Laurine",
"Laury",
"Lauryn",
"Lavada",
"Lavern",
"Laverna",
"Laverne",
"Lavina",
"Lavinia",
"Lavon",
"Lavonne",
"Lawrence",
"Lawson",
"Layla",
"Layne",
"Lazaro",
"Lea",
"Leann",
"Leanna",
"Leanne",
"Leatha",
"Leda",
"Lee",
"Leif",
"Leila",
"Leilani",
"Lela",
"Lelah",
"Leland",
"Lelia",
"Lempi",
"Lemuel",
"Lenna",
"Lennie",
"Lenny",
"Lenora",
"Lenore",
"Leo",
"Leola",
"Leon",
"Leonard",
"Leonardo",
"Leone",
"Leonel",
"Leonie",
"Leonor",
"Leonora",
"Leopold",
"Leopoldo",
"Leora",
"Lera",
"Lesley",
"Leslie",
"Lesly",
"Lessie",
"Lester",
"Leta",
"Letha",
"Letitia",
"Levi",
"Lew",
"Lewis",
"Lexi",
"Lexie",
"Lexus",
"Lia",
"Liam",
"Liana",
"Libbie",
"Libby",
"Lila",
"Lilian",
"Liliana",
"Liliane",
"Lilla",
"Lillian",
"Lilliana",
"Lillie",
"Lilly",
"Lily",
"Lilyan",
"Lina",
"Lincoln",
"Linda",
"Lindsay",
"Lindsey",
"Linnea",
"Linnie",
"Linwood",
"Lionel",
"Lisa",
"Lisandro",
"Lisette",
"Litzy",
"Liza",
"Lizeth",
"Lizzie",
"Llewellyn",
"Lloyd",
"Logan",
"Lois",
"Lola",
"Lolita",
"Loma",
"Lon",
"London",
"Lonie",
"Lonnie",
"Lonny",
"Lonzo",
"Lora",
"Loraine",
"Loren",
"Lorena",
"Lorenz",
"Lorenza",
"Lorenzo",
"Lori",
"Lorine",
"Lorna",
"Lottie",
"Lou",
"Louie",
"Louisa",
"Lourdes",
"Louvenia",
"Lowell",
"Loy",
"Loyal",
"Loyce",
"Lucas",
"Luciano",
"Lucie",
"Lucienne",
"Lucile",
"Lucinda",
"Lucio",
"Lucious",
"Lucius",
"Lucy",
"Ludie",
"Ludwig",
"Lue",
"Luella",
"Luigi",
"Luis",
"Luisa",
"Lukas",
"Lula",
"Lulu",
"Luna",
"Lupe",
"Lura",
"Lurline",
"Luther",
"Luz",
"Lyda",
"Lydia",
"Lyla",
"Lynn",
"Lyric",
"Lysanne",
"Mabel",
"Mabelle",
"Mable",
"Mac",
"Macey",
"Maci",
"Macie",
"Mack",
"Mackenzie",
"Macy",
"Madaline",
"Madalyn",
"Maddison",
"Madeline",
"Madelyn",
"Madelynn",
"Madge",
"Madie",
"Madilyn",
"Madisen",
"Madison",
"Madisyn",
"Madonna",
"Madyson",
"Mae",
"Maegan",
"Maeve",
"Mafalda",
"Magali",
"Magdalen",
"Magdalena",
"Maggie",
"Magnolia",
"Magnus",
"Maia",
"Maida",
"Maiya",
"Major",
"Makayla",
"Makenna",
"Makenzie",
"Malachi",
"Malcolm",
"Malika",
"Malinda",
"Mallie",
"Mallory",
"Malvina",
"Mandy",
"Manley",
"Manuel",
"Manuela",
"Mara",
"Marc",
"Marcel",
"Marcelina",
"Marcelino",
"Marcella",
"Marcelle",
"Marcellus",
"Marcelo",
"Marcia",
"Marco",
"Marcos",
"Marcus",
"Margaret",
"Margarete",
"Margarett",
"Margaretta",
"Margarette",
"Margarita",
"Marge",
"Margie",
"Margot",
"Margret",
"Marguerite",
"Maria",
"Mariah",
"Mariam",
"Marian",
"Mariana",
"Mariane",
"Marianna",
"Marianne",
"Mariano",
"Maribel",
"Marie",
"Mariela",
"Marielle",
"Marietta",
"Marilie",
"Marilou",
"Marilyne",
"Marina",
"Mario",
"Marion",
"Marisa",
"Marisol",
"Maritza",
"Marjolaine",
"Marjorie",
"Marjory",
"Mark",
"Markus",
"Marlee",
"Marlen",
"Marlene",
"Marley",
"Marlin",
"Marlon",
"Marques",
"Marquis",
"Marquise",
"Marshall",
"Marta",
"Martin",
"Martina",
"Martine",
"Marty",
"Marvin",
"Mary",
"Maryam",
"Maryjane",
"Maryse",
"Mason",
"Mateo",
"Mathew",
"Mathias",
"Mathilde",
"Matilda",
"Matilde",
"Matt",
"Matteo",
"Mattie",
"Maud",
"Maude",
"Maudie",
"Maureen",
"Maurice",
"Mauricio",
"Maurine",
"Maverick",
"Mavis",
"Max",
"Maxie",
"Maxime",
"Maximilian",
"Maximillia",
"Maximillian",
"Maximo",
"Maximus",
"Maxine",
"Maxwell",
"May",
"Maya",
"Maybell",
"Maybelle",
"Maye",
"Maymie",
"Maynard",
"Mayra",
"Mazie",
"Mckayla",
"Mckenna",
"Mckenzie",
"Meagan",
"Meaghan",
"Meda",
"Megane",
"Meggie",
"Meghan",
"Mekhi",
"Melany",
"Melba",
"Melisa",
"Melissa",
"Mellie",
"Melody",
"Melvin",
"Melvina",
"Melyna",
"Melyssa",
"Mercedes",
"Meredith",
"Merl",
"Merle",
"Merlin",
"Merritt",
"Mertie",
"Mervin",
"Meta",
"Mia",
"Micaela",
"Micah",
"Michael",
"Michaela",
"Michale",
"Micheal",
"Michel",
"Michele",
"Michelle",
"Miguel",
"Mikayla",
"Mike",
"Mikel",
"Milan",
"Miles",
"Milford",
"Miller",
"Millie",
"Milo",
"Milton",
"Mina",
"Minerva",
"Minnie",
"Miracle",
"Mireille",
"Mireya",
"Misael",
"Missouri",
"Misty",
"Mitchel",
"Mitchell",
"Mittie",
"Modesta",
"Modesto",
"Mohamed",
"Mohammad",
"Mohammed",
"Moises",
"Mollie",
"Molly",
"Mona",
"Monica",
"Monique",
"Monroe",
"Monserrat",
"Monserrate",
"Montana",
"Monte",
"Monty",
"Morgan",
"Moriah",
"Morris",
"Mortimer",
"Morton",
"Mose",
"Moses",
"Moshe",
"Mossie",
"Mozell",
"Mozelle",
"Muhammad",
"Muriel",
"Murl",
"Murphy",
"Murray",
"Mustafa",
"Mya",
"Myah",
"Mylene",
"Myles",
"Myra",
"Myriam",
"Myrl",
"Myrna",
"Myron",
"Myrtice",
"Myrtie",
"Myrtis",
"Myrtle",
"Nadia",
"Nakia",
"Name",
"Nannie",
"Naomi",
"Naomie",
"Napoleon",
"Narciso",
"Nash",
"Nasir",
"Nat",
"Natalia",
"Natalie",
"Natasha",
"Nathan",
"Nathanael",
"Nathanial",
"Nathaniel",
"Nathen",
"Nayeli",
"Neal",
"Ned",
"Nedra",
"Neha",
"Neil",
"Nelda",
"Nella",
"Nelle",
"Nellie",
"Nels",
"Nelson",
"Neoma",
"Nestor",
"Nettie",
"Neva",
"Newell",
"Newton",
"Nia",
"Nicholas",
"Nicholaus",
"Nichole",
"Nick",
"Nicklaus",
"Nickolas",
"Nico",
"Nicola",
"Nicolas",
"Nicole",
"Nicolette",
"Nigel",
"Nikita",
"Nikki",
"Nikko",
"Niko",
"Nikolas",
"Nils",
"Nina",
"Noah",
"Noble",
"Noe",
"Noel",
"Noelia",
"Noemi",
"Noemie",
"Noemy",
"Nola",
"Nolan",
"Nona",
"Nora",
"Norbert",
"Norberto",
"Norene",
"Norma",
"Norris",
"Norval",
"Norwood",
"Nova",
"Novella",
"Nya",
"Nyah",
"Nyasia",
"Obie",
"Oceane",
"Ocie",
"Octavia",
"Oda",
"Odell",
"Odessa",
"Odie",
"Ofelia",
"Okey",
"Ola",
"Olaf",
"Ole",
"Olen",
"Oleta",
"Olga",
"Olin",
"Oliver",
"Ollie",
"Oma",
"Omari",
"Omer",
"Ona",
"Onie",
"Opal",
"Ophelia",
"Ora",
"Oral",
"Oran",
"Oren",
"Orie",
"Orin",
"Orion",
"Orland",
"Orlando",
"Orlo",
"Orpha",
"Orrin",
"Orval",
"Orville",
"Osbaldo",
"Osborne",
"Oscar",
"Osvaldo",
"Oswald",
"Oswaldo",
"Otha",
"Otho",
"Otilia",
"Otis",
"Ottilie",
"Ottis",
"Otto",
"Ova",
"Owen",
"Ozella",
"Pablo",
"Paige",
"Palma",
"Pamela",
"Pansy",
"Paolo",
"Paris",
"Parker",
"Pascale",
"Pasquale",
"Pat",
"Patience",
"Patricia",
"Patrick",
"Patsy",
"Pattie",
"Paul",
"Paula",
"Pauline",
"Paxton",
"Payton",
"Pearl",
"Pearlie",
"Pearline",
"Pedro",
"Peggie",
"Penelope",
"Percival",
"Percy",
"Perry",
"Pete",
"Peter",
"Petra",
"Peyton",
"Philip",
"Phoebe",
"Phyllis",
"Pierce",
"Pierre",
"Pietro",
"Pink",
"Pinkie",
"Piper",
"Polly",
"Porter",
"Precious",
"Presley",
"Preston",
"Price",
"Prince",
"Princess",
"Priscilla",
"Providenci",
"Prudence",
"Queen",
"Queenie",
"Quentin",
"Quincy",
"Quinn",
"Quinten",
"Quinton",
"Rachael",
"Rachel",
"Rachelle",
"Rae",
"Raegan",
"Rafael",
"Rafaela",
"Raheem",
"Rahsaan",
"Rahul",
"Raina",
"Raleigh",
"Ralph",
"Ramiro",
"Ramon",
"Ramona",
"Randal",
"Randall",
"Randi",
"Randy",
"Ransom",
"Raoul",
"Raphael",
"Raphaelle",
"Raquel",
"Rashad",
"Rashawn",
"Rasheed",
"Raul",
"Raven",
"Ray",
"Raymond",
"Raymundo",
"Reagan",
"Reanna",
"Reba",
"Rebeca",
"Rebecca",
"Rebeka",
"Rebekah",
"Reece",
"Reed",
"Reese",
"Regan",
"Reggie",
"Reginald",
"Reid",
"Reilly",
"Reina",
"Reinhold",
"Remington",
"Rene",
"Renee",
"Ressie",
"Reta",
"Retha",
"Retta",
"Reuben",
"Reva",
"Rex",
"Rey",
"Reyes",
"Reymundo",
"Reyna",
"Reynold",
"Rhea",
"Rhett",
"Rhianna",
"Rhiannon",
"Rhoda",
"Ricardo",
"Richard",
"Richie",
"Richmond",
"Rick",
"Rickey",
"Rickie",
"Ricky",
"Rico",
"Rigoberto",
"Riley",
"Rita",
"River",
"Robb",
"Robbie",
"Robert",
"Roberta",
"Roberto",
"Robin",
"Robyn",
"Rocio",
"Rocky",
"Rod",
"Roderick",
"Rodger",
"Rodolfo",
"Rodrick",
"Rodrigo",
"Roel",
"Rogelio",
"Roger",
"Rogers",
"Rolando",
"Rollin",
"Roma",
"Romaine",
"Roman",
"Ron",
"Ronaldo",
"Ronny",
"Roosevelt",
"Rory",
"Rosa",
"Rosalee",
"Rosalia",
"Rosalind",
"Rosalinda",
"Rosalyn",
"Rosamond",
"Rosanna",
"Rosario",
"Roscoe",
"Rose",
"Rosella",
"Roselyn",
"Rosemarie",
"Rosemary",
"Rosendo",
"Rosetta",
"Rosie",
"Rosina",
"Roslyn",
"Ross",
"Rossie",
"Rowan",
"Rowena",
"Rowland",
"Roxane",
"Roxanne",
"Roy",
"Royal",
"Royce",
"Rozella",
"Ruben",
"Rubie",
"Ruby",
"Rubye",
"Rudolph",
"Rudy",
"Rupert",
"Russ",
"Russel",
"Russell",
"Rusty",
"Ruth",
"Ruthe",
"Ruthie",
"Ryan",
"Ryann",
"Ryder",
"Rylan",
"Rylee",
"Ryleigh",
"Ryley",
"Sabina",
"Sabrina",
"Sabryna",
"Sadie",
"Sadye",
"Sage",
"Saige",
"Sallie",
"Sally",
"Salma",
"Salvador",
"Salvatore",
"Sam",
"Samanta",
"Samantha",
"Samara",
"Samir",
"Sammie",
"Sammy",
"Samson",
"Sandra",
"Sandrine",
"Sandy",
"Sanford",
"Santa",
"Santiago",
"Santina",
"Santino",
"Santos",
"Sarah",
"Sarai",
"Sarina",
"Sasha",
"Saul",
"Savanah",
"Savanna",
"Savannah",
"Savion",
"Scarlett",
"Schuyler",
"Scot",
"Scottie",
"Scotty",
"Seamus",
"Sean",
"Sebastian",
"Sedrick",
"Selena",
"Selina",
"Selmer",
"Serena",
"Serenity",
"Seth",
"Shad",
"Shaina",
"Shakira",
"Shana",
"Shane",
"Shanel",
"Shanelle",
"Shania",
"Shanie",
"Shaniya",
"Shanna",
"Shannon",
"Shanny",
"Shanon",
"Shany",
"Sharon",
"Shaun",
"Shawn",
"Shawna",
"Shaylee",
"Shayna",
"Shayne",
"Shea",
"Sheila",
"Sheldon",
"Shemar",
"Sheridan",
"Sherman",
"Sherwood",
"Shirley",
"Shyann",
"Shyanne",
"Sibyl",
"Sid",
"Sidney",
"Sienna",
"Sierra",
"Sigmund",
"Sigrid",
"Sigurd",
"Silas",
"Sim",
"Simeon",
"Simone",
"Sincere",
"Sister",
"Skye",
"Skyla",
"Skylar",
"Sofia",
"Soledad",
"Solon",
"Sonia",
"Sonny",
"Sonya",
"Sophia",
"Sophie",
"Spencer",
"Stacey",
"Stacy",
"Stan",
"Stanford",
"Stanley",
"Stanton",
"Stefan",
"Stefanie",
"Stella",
"Stephan",
"Stephania",
"Stephanie",
"Stephany",
"Stephen",
"Stephon",
"Sterling",
"Steve",
"Stevie",
"Stewart",
"Stone",
"Stuart",
"Summer",
"Sunny",
"Susan",
"Susana",
"Susanna",
"Susie",
"Suzanne",
"Sven",
"Syble",
"Sydnee",
"Sydney",
"Sydni",
"Sydnie",
"Sylvan",
"Sylvester",
"Sylvia",
"Tabitha",
"Tad",
"Talia",
"Talon",
"Tamara",
"Tamia",
"Tania",
"Tanner",
"Tanya",
"Tara",
"Taryn",
"Tate",
"Tatum",
"Tatyana",
"Taurean",
"Tavares",
"Taya",
"Taylor",
"Teagan",
"Ted",
"Telly",
"Terence",
"Teresa",
"Terrance",
"Terrell",
"Terrence",
"Terrill",
"Terry",
"Tess",
"Tessie",
"Tevin",
"Thad",
"Thaddeus",
"Thalia",
"Thea",
"Thelma",
"Theo",
"Theodora",
"Theodore",
"Theresa",
"Therese",
"Theresia",
"Theron",
"Thomas",
"Thora",
"Thurman",
"Tia",
"Tiana",
"Tianna",
"Tiara",
"Tierra",
"Tiffany",
"Tillman",
"Timmothy",
"Timmy",
"Timothy",
"Tina",
"Tito",
"Titus",
"Tobin",
"Toby",
"Tod",
"Tom",
"Tomas",
"Tomasa",
"Tommie",
"Toney",
"Toni",
"Tony",
"Torey",
"Torrance",
"Torrey",
"Toy",
"Trace",
"Tracey",
"Tracy",
"Travis",
"Travon",
"Tre",
"Tremaine",
"Tremayne",
"Trent",
"Trenton",
"Tressa",
"Tressie",
"Treva",
"Trever",
"Trevion",
"Trevor",
"Trey",
"Trinity",
"Trisha",
"Tristian",
"Tristin",
"Triston",
"Troy",
"Trudie",
"Trycia",
"Trystan",
"Turner",
"Twila",
"Tyler",
"Tyra",
"Tyree",
"Tyreek",
"Tyrel",
"Tyrell",
"Tyrese",
"Tyrique",
"Tyshawn",
"Tyson",
"Ubaldo",
"Ulices",
"Ulises",
"Una",
"Unique",
"Urban",
"Uriah",
"Uriel",
"Ursula",
"Vada",
"Valentin",
"Valentina",
"Valentine",
"Valerie",
"Vallie",
"Van",
"Vance",
"Vanessa",
"Vaughn",
"Veda",
"Velda",
"Vella",
"Velma",
"Velva",
"Vena",
"Verda",
"Verdie",
"Vergie",
"Verla",
"Verlie",
"Vern",
"Verna",
"Verner",
"Vernice",
"Vernie",
"Vernon",
"Verona",
"Veronica",
"Vesta",
"Vicenta",
"Vicente",
"Vickie",
"Vicky",
"Victor",
"Victoria",
"Vida",
"Vidal",
"Vilma",
"Vince",
"Vincent",
"Vincenza",
"Vincenzo",
"Vinnie",
"Viola",
"Violet",
"Violette",
"Virgie",
"Virgil",
"Virginia",
"Virginie",
"Vita",
"Vito",
"Viva",
"Vivian",
"Viviane",
"Vivianne",
"Vivien",
"Vivienne",
"Vladimir",
"Wade",
"Waino",
"Waldo",
"Walker",
"Wallace",
"Walter",
"Walton",
"Wanda",
"Ward",
"Warren",
"Watson",
"Wava",
"Waylon",
"Wayne",
"Webster",
"Weldon",
"Wellington",
"Wendell",
"Wendy",
"Werner",
"Westley",
"Weston",
"Whitney",
"Wilber",
"Wilbert",
"Wilburn",
"Wiley",
"Wilford",
"Wilfred",
"Wilfredo",
"Wilfrid",
"Wilhelm",
"Wilhelmine",
"Will",
"Willa",
"Willard",
"William",
"Willie",
"Willis",
"Willow",
"Willy",
"Wilma",
"Wilmer",
"Wilson",
"Wilton",
"Winfield",
"Winifred",
"Winnifred",
"Winona",
"Winston",
"Woodrow",
"Wyatt",
"Wyman",
"Xander",
"Xavier",
"Xzavier",
"Yadira",
"Yasmeen",
"Yasmin",
"Yasmine",
"Yazmin",
"Yesenia",
"Yessenia",
"Yolanda",
"Yoshiko",
"Yvette",
"Yvonne",
"Zachariah",
"Zachary",
"Zachery",
"Zack",
"Zackary",
"Zackery",
"Zakary",
"Zander",
"Zane",
"Zaria",
"Zechariah",
"Zelda",
"Zella",
"Zelma",
"Zena",
"Zetta",
"Zion",
"Zita",
"Zoe",
"Zoey",
"Zoie",
"Zoila",
"Zola",
"Zora",
"Zula"
];
},{}],111:[function(require,module,exports){
var name = {};
module['exports'] = name;
name.first_name = require("./first_name");
name.last_name = require("./last_name");
name.prefix = require("./prefix");
name.suffix = require("./suffix");
name.title = require("./title");
name.name = require("./name");
},{"./first_name":110,"./last_name":112,"./name":113,"./prefix":114,"./suffix":115,"./title":116}],112:[function(require,module,exports){
module["exports"] = [
"Abbott",
"Abernathy",
"Abshire",
"Adams",
"Altenwerth",
"Anderson",
"Ankunding",
"Armstrong",
"Auer",
"Aufderhar",
"Bahringer",
"Bailey",
"Balistreri",
"Barrows",
"Bartell",
"Bartoletti",
"Barton",
"Bashirian",
"Batz",
"Bauch",
"Baumbach",
"Bayer",
"Beahan",
"Beatty",
"Bechtelar",
"Becker",
"Bednar",
"Beer",
"Beier",
"Berge",
"Bergnaum",
"Bergstrom",
"Bernhard",
"Bernier",
"Bins",
"Blanda",
"Blick",
"Block",
"Bode",
"Boehm",
"Bogan",
"Bogisich",
"Borer",
"Bosco",
"Botsford",
"Boyer",
"Boyle",
"Bradtke",
"Brakus",
"Braun",
"Breitenberg",
"Brekke",
"Brown",
"Bruen",
"Buckridge",
"Carroll",
"Carter",
"Cartwright",
"Casper",
"Cassin",
"Champlin",
"Christiansen",
"Cole",
"Collier",
"Collins",
"Conn",
"Connelly",
"Conroy",
"Considine",
"Corkery",
"Cormier",
"Corwin",
"Cremin",
"Crist",
"Crona",
"Cronin",
"Crooks",
"Cruickshank",
"Cummerata",
"Cummings",
"Dach",
"D'Amore",
"Daniel",
"Dare",
"Daugherty",
"Davis",
"Deckow",
"Denesik",
"Dibbert",
"Dickens",
"Dicki",
"Dickinson",
"Dietrich",
"Donnelly",
"Dooley",
"Douglas",
"Doyle",
"DuBuque",
"Durgan",
"Ebert",
"Effertz",
"Eichmann",
"Emard",
"Emmerich",
"Erdman",
"Ernser",
"Fadel",
"Fahey",
"Farrell",
"Fay",
"Feeney",
"Feest",
"Feil",
"Ferry",
"Fisher",
"Flatley",
"Frami",
"Franecki",
"Friesen",
"Fritsch",
"Funk",
"Gaylord",
"Gerhold",
"Gerlach",
"Gibson",
"Gislason",
"Gleason",
"Gleichner",
"Glover",
"Goldner",
"Goodwin",
"Gorczany",
"Gottlieb",
"Goyette",
"Grady",
"Graham",
"Grant",
"Green",
"Greenfelder",
"Greenholt",
"Grimes",
"Gulgowski",
"Gusikowski",
"Gutkowski",
"Gutmann",
"Haag",
"Hackett",
"Hagenes",
"Hahn",
"Haley",
"Halvorson",
"Hamill",
"Hammes",
"Hand",
"Hane",
"Hansen",
"Harber",
"Harris",
"Hartmann",
"Harvey",
"Hauck",
"Hayes",
"Heaney",
"Heathcote",
"Hegmann",
"Heidenreich",
"Heller",
"Herman",
"Hermann",
"Hermiston",
"Herzog",
"Hessel",
"Hettinger",
"Hickle",
"Hilll",
"Hills",
"Hilpert",
"Hintz",
"Hirthe",
"Hodkiewicz",
"Hoeger",
"Homenick",
"Hoppe",
"Howe",
"Howell",
"Hudson",
"Huel",
"Huels",
"Hyatt",
"Jacobi",
"Jacobs",
"Jacobson",
"Jakubowski",
"Jaskolski",
"Jast",
"Jenkins",
"Jerde",
"Johns",
"Johnson",
"Johnston",
"Jones",
"Kassulke",
"Kautzer",
"Keebler",
"Keeling",
"Kemmer",
"Kerluke",
"Kertzmann",
"Kessler",
"Kiehn",
"Kihn",
"Kilback",
"King",
"Kirlin",
"Klein",
"Kling",
"Klocko",
"Koch",
"Koelpin",
"Koepp",
"Kohler",
"Konopelski",
"Koss",
"Kovacek",
"Kozey",
"Krajcik",
"Kreiger",
"Kris",
"Kshlerin",
"Kub",
"Kuhic",
"Kuhlman",
"Kuhn",
"Kulas",
"Kunde",
"Kunze",
"Kuphal",
"Kutch",
"Kuvalis",
"Labadie",
"Lakin",
"Lang",
"Langosh",
"Langworth",
"Larkin",
"Larson",
"Leannon",
"Lebsack",
"Ledner",
"Leffler",
"Legros",
"Lehner",
"Lemke",
"Lesch",
"Leuschke",
"Lind",
"Lindgren",
"Littel",
"Little",
"Lockman",
"Lowe",
"Lubowitz",
"Lueilwitz",
"Luettgen",
"Lynch",
"Macejkovic",
"MacGyver",
"Maggio",
"Mann",
"Mante",
"Marks",
"Marquardt",
"Marvin",
"Mayer",
"Mayert",
"McClure",
"McCullough",
"McDermott",
"McGlynn",
"McKenzie",
"McLaughlin",
"Medhurst",
"Mertz",
"Metz",
"Miller",
"Mills",
"Mitchell",
"Moen",
"Mohr",
"Monahan",
"Moore",
"Morar",
"Morissette",
"Mosciski",
"Mraz",
"Mueller",
"Muller",
"Murazik",
"Murphy",
"Murray",
"Nader",
"Nicolas",
"Nienow",
"Nikolaus",
"Nitzsche",
"Nolan",
"Oberbrunner",
"O'Connell",
"O'Conner",
"O'Hara",
"O'Keefe",
"O'Kon",
"Okuneva",
"Olson",
"Ondricka",
"O'Reilly",
"Orn",
"Ortiz",
"Osinski",
"Pacocha",
"Padberg",
"Pagac",
"Parisian",
"Parker",
"Paucek",
"Pfannerstill",
"Pfeffer",
"Pollich",
"Pouros",
"Powlowski",
"Predovic",
"Price",
"Prohaska",
"Prosacco",
"Purdy",
"Quigley",
"Quitzon",
"Rath",
"Ratke",
"Rau",
"Raynor",
"Reichel",
"Reichert",
"Reilly",
"Reinger",
"Rempel",
"Renner",
"Reynolds",
"Rice",
"Rippin",
"Ritchie",
"Robel",
"Roberts",
"Rodriguez",
"Rogahn",
"Rohan",
"Rolfson",
"Romaguera",
"Roob",
"Rosenbaum",
"Rowe",
"Ruecker",
"Runolfsdottir",
"Runolfsson",
"Runte",
"Russel",
"Rutherford",
"Ryan",
"Sanford",
"Satterfield",
"Sauer",
"Sawayn",
"Schaden",
"Schaefer",
"Schamberger",
"Schiller",
"Schimmel",
"Schinner",
"Schmeler",
"Schmidt",
"Schmitt",
"Schneider",
"Schoen",
"Schowalter",
"Schroeder",
"Schulist",
"Schultz",
"Schumm",
"Schuppe",
"Schuster",
"Senger",
"Shanahan",
"Shields",
"Simonis",
"Sipes",
"Skiles",
"Smith",
"Smitham",
"Spencer",
"Spinka",
"Sporer",
"Stamm",
"Stanton",
"Stark",
"Stehr",
"Steuber",
"Stiedemann",
"Stokes",
"Stoltenberg",
"Stracke",
"Streich",
"Stroman",
"Strosin",
"Swaniawski",
"Swift",
"Terry",
"Thiel",
"Thompson",
"Tillman",
"Torp",
"Torphy",
"Towne",
"Toy",
"Trantow",
"Tremblay",
"Treutel",
"Tromp",
"Turcotte",
"Turner",
"Ullrich",
"Upton",
"Vandervort",
"Veum",
"Volkman",
"Von",
"VonRueden",
"Waelchi",
"Walker",
"Walsh",
"Walter",
"Ward",
"Waters",
"Watsica",
"Weber",
"Wehner",
"Weimann",
"Weissnat",
"Welch",
"West",
"White",
"Wiegand",
"Wilderman",
"Wilkinson",
"Will",
"Williamson",
"Willms",
"Windler",
"Wintheiser",
"Wisoky",
"Wisozk",
"Witting",
"Wiza",
"Wolf",
"Wolff",
"Wuckert",
"Wunsch",
"Wyman",
"Yost",
"Yundt",
"Zboncak",
"Zemlak",
"Ziemann",
"Zieme",
"Zulauf"
];
},{}],113:[function(require,module,exports){
module["exports"] = [
"#{prefix} #{first_name} #{last_name}",
"#{first_name} #{last_name} #{suffix}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}"
];
},{}],114:[function(require,module,exports){
module["exports"] = [
"Mr.",
"Mrs.",
"Ms.",
"Miss",
"Dr."
];
},{}],115:[function(require,module,exports){
module["exports"] = [
"Jr.",
"Sr.",
"I",
"II",
"III",
"IV",
"V",
"MD",
"DDS",
"PhD",
"DVM"
];
},{}],116:[function(require,module,exports){
module["exports"] = {
"descriptor": [
"Lead",
"Senior",
"Direct",
"Corporate",
"Dynamic",
"Future",
"Product",
"National",
"Regional",
"District",
"Central",
"Global",
"Customer",
"Investor",
"Dynamic",
"International",
"Legacy",
"Forward",
"Internal",
"Human",
"Chief",
"Principal"
],
"level": [
"Solutions",
"Program",
"Brand",
"Security",
"Research",
"Marketing",
"Directives",
"Implementation",
"Integration",
"Functionality",
"Response",
"Paradigm",
"Tactics",
"Identity",
"Markets",
"Group",
"Division",
"Applications",
"Optimization",
"Operations",
"Infrastructure",
"Intranet",
"Communications",
"Web",
"Branding",
"Quality",
"Assurance",
"Mobility",
"Accounts",
"Data",
"Creative",
"Configuration",
"Accountability",
"Interactions",
"Factors",
"Usability",
"Metrics"
],
"job": [
"Supervisor",
"Associate",
"Executive",
"Liason",
"Officer",
"Manager",
"Engineer",
"Specialist",
"Director",
"Coordinator",
"Administrator",
"Architect",
"Analyst",
"Designer",
"Planner",
"Orchestrator",
"Technician",
"Developer",
"Producer",
"Consultant",
"Assistant",
"Facilitator",
"Agent",
"Representative",
"Strategist"
]
};
},{}],117:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-#### x###",
"(###) ###-#### x###",
"1-###-###-#### x###",
"###.###.#### x###",
"###-###-#### x####",
"(###) ###-#### x####",
"1-###-###-#### x####",
"###.###.#### x####",
"###-###-#### x#####",
"(###) ###-#### x#####",
"1-###-###-#### x#####",
"###.###.#### x#####"
];
},{}],118:[function(require,module,exports){
var phone_number = {};
module['exports'] = phone_number;
phone_number.formats = require("./formats");
},{"./formats":117}],119:[function(require,module,exports){
module["exports"] = [
"ants",
"bats",
"bears",
"bees",
"birds",
"buffalo",
"cats",
"chickens",
"cattle",
"dogs",
"dolphins",
"ducks",
"elephants",
"fishes",
"foxes",
"frogs",
"geese",
"goats",
"horses",
"kangaroos",
"lions",
"monkeys",
"owls",
"oxen",
"penguins",
"people",
"pigs",
"rabbits",
"sheep",
"tigers",
"whales",
"wolves",
"zebras",
"banshees",
"crows",
"black cats",
"chimeras",
"ghosts",
"conspirators",
"dragons",
"dwarves",
"elves",
"enchanters",
"exorcists",
"sons",
"foes",
"giants",
"gnomes",
"goblins",
"gooses",
"griffins",
"lycanthropes",
"nemesis",
"ogres",
"oracles",
"prophets",
"sorcerors",
"spiders",
"spirits",
"vampires",
"warlocks",
"vixens",
"werewolves",
"witches",
"worshipers",
"zombies",
"druids"
];
},{}],120:[function(require,module,exports){
var team = {};
module['exports'] = team;
team.creature = require("./creature");
team.name = require("./name");
},{"./creature":119,"./name":121}],121:[function(require,module,exports){
module["exports"] = [
"#{Address.state} #{creature}"
];
},{}],122:[function(require,module,exports){
arguments[4][37][0].apply(exports,arguments)
},{"dup":37}],123:[function(require,module,exports){
module["exports"] = [
"#{city_name}"
];
},{}],124:[function(require,module,exports){
module["exports"] = [
"Aleksandrów Kujawski",
"Aleksandrów Łódzki",
"Alwernia",
"Andrychów",
"Annopol",
"Augustów",
"Babimost",
"Baborów",
"Baranów Sandomierski",
"Barcin",
"Barczewo",
"Bardo",
"Barlinek",
"Bartoszyce",
"Barwice",
"Bełchatów",
"Bełżyce",
"Będzin",
"Biała",
"Biała Piska",
"Biała Podlaska",
"Biała Rawska",
"Białobrzegi",
"Białogard",
"Biały Bór",
"Białystok",
"Biecz",
"Bielawa",
"Bielsk Podlaski",
"Bielsko-Biała",
"Bieruń",
"Bierutów",
"Bieżuń",
"Biłgoraj",
"Biskupiec",
"Bisztynek",
"Blachownia",
"Błaszki",
"Błażowa",
"Błonie",
"Bobolice",
"Bobowa",
"Bochnia",
"Bodzentyn",
"Bogatynia",
"Boguchwała",
"Boguszów-Gorce",
"Bojanowo",
"Bolesławiec",
"Bolków",
"Borek Wielkopolski",
"Borne Sulinowo",
"Braniewo",
"Brańsk",
"Brodnica",
"Brok",
"Brusy",
"Brwinów",
"Brzeg",
"Brzeg Dolny",
"Brzesko",
"Brzeszcze",
"Brześć Kujawski",
"Brzeziny",
"Brzostek",
"Brzozów",
"Buk",
"Bukowno",
"Busko-Zdrój",
"Bychawa",
"Byczyna",
"Bydgoszcz",
"Bystrzyca Kłodzka",
"Bytom",
"Bytom Odrzański",
"Bytów",
"Cedynia",
"Chełm",
"Chełmek",
"Chełmno",
"Chełmża",
"Chęciny",
"Chmielnik",
"Chocianów",
"Chociwel",
"Chodecz",
"Chodzież",
"Chojna",
"Chojnice",
"Chojnów",
"Choroszcz",
"Chorzele",
"Chorzów",
"Choszczno",
"Chrzanów",
"Ciechanowiec",
"Ciechanów",
"Ciechocinek",
"Cieszanów",
"Cieszyn",
"Ciężkowice",
"Cybinka",
"Czaplinek",
"Czarna Białostocka",
"Czarna Woda",
"Czarne",
"Czarnków",
"Czchów",
"Czechowice-Dziedzice",
"Czeladź",
"Czempiń",
"Czerniejewo",
"Czersk",
"Czerwieńsk",
"Czerwionka-Leszczyny",
"Częstochowa",
"Człopa",
"Człuchów",
"Czyżew",
"Ćmielów",
"Daleszyce",
"Darłowo",
"Dąbie",
"Dąbrowa Białostocka",
"Dąbrowa Górnicza",
"Dąbrowa Tarnowska",
"Debrzno",
"Dębica",
"Dęblin",
"Dębno",
"Dobczyce",
"Dobiegniew",
"Dobra (powiat łobeski)",
"Dobra (powiat turecki)",
"Dobre Miasto",
"Dobrodzień",
"Dobrzany",
"Dobrzyń nad Wisłą",
"Dolsk",
"Drawno",
"Drawsko Pomorskie",
"Drezdenko",
"Drobin",
"Drohiczyn",
"Drzewica",
"Dukla",
"Duszniki-Zdrój",
"Dynów",
"Działdowo",
"Działoszyce",
"Działoszyn",
"Dzierzgoń",
"Dzierżoniów",
"Dziwnów",
"Elbląg",
"Ełk",
"Frampol",
"Frombork",
"Garwolin",
"Gąbin",
"Gdańsk",
"Gdynia",
"Giżycko",
"Glinojeck",
"Gliwice",
"Głogów",
"Głogów Małopolski",
"Głogówek",
"Głowno",
"Głubczyce",
"Głuchołazy",
"Głuszyca",
"Gniew",
"Gniewkowo",
"Gniezno",
"Gogolin",
"Golczewo",
"Goleniów",
"Golina",
"Golub-Dobrzyń",
"Gołańcz",
"Gołdap",
"Goniądz",
"Gorlice",
"Gorzów Śląski",
"Gorzów Wielkopolski",
"Gostynin",
"Gostyń",
"Gościno",
"Gozdnica",
"Góra",
"Góra Kalwaria",
"Górowo Iławeckie",
"Górzno",
"Grabów nad Prosną",
"Grajewo",
"Grodków",
"Grodzisk Mazowiecki",
"Grodzisk Wielkopolski",
"Grójec",
"Grudziądz",
"Grybów",
"Gryfice",
"Gryfino",
"Gryfów Śląski",
"Gubin",
"Hajnówka",
"Halinów",
"Hel",
"Hrubieszów",
"Iława",
"Iłowa",
"Iłża",
"Imielin",
"Inowrocław",
"Ińsko",
"Iwonicz-Zdrój",
"Izbica Kujawska",
"Jabłonowo Pomorskie",
"Janikowo",
"Janowiec Wielkopolski",
"Janów Lubelski",
"Jarocin",
"Jarosław",
"Jasień",
"Jasło",
"Jastarnia",
"Jastrowie",
"Jastrzębie-Zdrój",
"Jawor",
"Jaworzno",
"Jaworzyna Śląska",
"Jedlicze",
"Jedlina-Zdrój",
"Jedwabne",
"Jelcz-Laskowice",
"Jelenia Góra",
"Jeziorany",
"Jędrzejów",
"Jordanów",
"Józefów (powiat biłgorajski)",
"Józefów (powiat otwocki)",
"Jutrosin",
"Kalety",
"Kalisz",
"Kalisz Pomorski",
"Kalwaria Zebrzydowska",
"Kałuszyn",
"Kamienna Góra",
"Kamień Krajeński",
"Kamień Pomorski",
"Kamieńsk",
"Kańczuga",
"Karczew",
"Kargowa",
"Karlino",
"Karpacz",
"Kartuzy",
"Katowice",
"Kazimierz Dolny",
"Kazimierza Wielka",
"Kąty Wrocławskie",
"Kcynia",
"Kędzierzyn-Koźle",
"Kępice",
"Kępno",
"Kętrzyn",
"Kęty",
"Kielce",
"Kietrz",
"Kisielice",
"Kleczew",
"Kleszczele",
"Kluczbork",
"Kłecko",
"Kłobuck",
"Kłodawa",
"Kłodzko",
"Knurów",
"Knyszyn",
"Kobylin",
"Kobyłka",
"Kock",
"Kolbuszowa",
"Kolno",
"Kolonowskie",
"Koluszki",
"Kołaczyce",
"Koło",
"Kołobrzeg",
"Koniecpol",
"Konin",
"Konstancin-Jeziorna",
"Konstantynów Łódzki",
"Końskie",
"Koprzywnica",
"Korfantów",
"Koronowo",
"Korsze",
"Kosów Lacki",
"Kostrzyn",
"Kostrzyn nad Odrą",
"Koszalin",
"Kościan",
"Kościerzyna",
"Kowal",
"Kowalewo Pomorskie",
"Kowary",
"Koziegłowy",
"Kozienice",
"Koźmin Wielkopolski",
"Kożuchów",
"Kórnik",
"Krajenka",
"Kraków",
"Krapkowice",
"Krasnobród",
"Krasnystaw",
"Kraśnik",
"Krobia",
"Krosno",
"Krosno Odrzańskie",
"Krośniewice",
"Krotoszyn",
"Kruszwica",
"Krynica Morska",
"Krynica-Zdrój",
"Krynki",
"Krzanowice",
"Krzepice",
"Krzeszowice",
"Krzywiń",
"Krzyż Wielkopolski",
"Książ Wielkopolski",
"Kudowa-Zdrój",
"Kunów",
"Kutno",
"Kuźnia Raciborska",
"Kwidzyn",
"Lądek-Zdrój",
"Legionowo",
"Legnica",
"Lesko",
"Leszno",
"Leśna",
"Leśnica",
"Lewin Brzeski",
"Leżajsk",
"Lębork",
"Lędziny",
"Libiąż",
"Lidzbark",
"Lidzbark Warmiński",
"Limanowa",
"Lipiany",
"Lipno",
"Lipsk",
"Lipsko",
"Lubaczów",
"Lubań",
"Lubartów",
"Lubawa",
"Lubawka",
"Lubień Kujawski",
"Lubin",
"Lublin",
"Lubliniec",
"Lubniewice",
"Lubomierz",
"Luboń",
"Lubraniec",
"Lubsko",
"Lwówek",
"Lwówek Śląski",
"Łabiszyn",
"Łańcut",
"Łapy",
"Łasin",
"Łask",
"Łaskarzew",
"Łaszczów",
"Łaziska Górne",
"Łazy",
"Łeba",
"Łęczna",
"Łęczyca",
"Łęknica",
"Łobez",
"Łobżenica",
"Łochów",
"Łomianki",
"Łomża",
"Łosice",
"Łowicz",
"Łódź",
"Łuków",
"Maków Mazowiecki",
"Maków Podhalański",
"Malbork",
"Małogoszcz",
"Małomice",
"Margonin",
"Marki",
"Maszewo",
"Miasteczko Śląskie",
"Miastko",
"Michałowo",
"Miechów",
"Miejska Górka",
"Mielec",
"Mieroszów",
"Mieszkowice",
"Międzybórz",
"Międzychód",
"Międzylesie",
"Międzyrzec Podlaski",
"Międzyrzecz",
"Międzyzdroje",
"Mikołajki",
"Mikołów",
"Mikstat",
"Milanówek",
"Milicz",
"Miłakowo",
"Miłomłyn",
"Miłosław",
"Mińsk Mazowiecki",
"Mirosławiec",
"Mirsk",
"Mława",
"Młynary",
"Mogielnica",
"Mogilno",
"Mońki",
"Morąg",
"Mordy",
"Moryń",
"Mosina",
"Mrągowo",
"Mrocza",
"Mszana Dolna",
"Mszczonów",
"Murowana Goślina",
"Muszyna",
"Mysłowice",
"Myszków",
"Myszyniec",
"Myślenice",
"Myślibórz",
"Nakło nad Notecią",
"Nałęczów",
"Namysłów",
"Narol",
"Nasielsk",
"Nekla",
"Nidzica",
"Niemcza",
"Niemodlin",
"Niepołomice",
"Nieszawa",
"Nisko",
"Nowa Dęba",
"Nowa Ruda",
"Nowa Sarzyna",
"Nowa Sól",
"Nowe",
"Nowe Brzesko",
"Nowe Miasteczko",
"Nowe Miasto Lubawskie",
"Nowe Miasto nad Pilicą",
"Nowe Skalmierzyce",
"Nowe Warpno",
"Nowogard",
"Nowogrodziec",
"Nowogród",
"Nowogród Bobrzański",
"Nowy Dwór Gdański",
"Nowy Dwór Mazowiecki",
"Nowy Sącz",
"Nowy Staw",
"Nowy Targ",
"Nowy Tomyśl",
"Nowy Wiśnicz",
"Nysa",
"Oborniki",
"Oborniki Śląskie",
"Obrzycko",
"Odolanów",
"Ogrodzieniec",
"Okonek",
"Olecko",
"Olesno",
"Oleszyce",
"Oleśnica",
"Olkusz",
"Olsztyn",
"Olsztynek",
"Olszyna",
"Oława",
"Opalenica",
"Opatów",
"Opoczno",
"Opole",
"Opole Lubelskie",
"Orneta",
"Orzesze",
"Orzysz",
"Osieczna",
"Osiek",
"Ostrołęka",
"Ostroróg",
"Ostrowiec Świętokrzyski",
"Ostróda",
"Ostrów Lubelski",
"Ostrów Mazowiecka",
"Ostrów Wielkopolski",
"Ostrzeszów",
"Ośno Lubuskie",
"Oświęcim",
"Otmuchów",
"Otwock",
"Ozimek",
"Ozorków",
"Ożarów",
"Ożarów Mazowiecki",
"Pabianice",
"Paczków",
"Pajęczno",
"Pakość",
"Parczew",
"Pasłęk",
"Pasym",
"Pelplin",
"Pełczyce",
"Piaseczno",
"Piaski",
"Piastów",
"Piechowice",
"Piekary Śląskie",
"Pieniężno",
"Pieńsk",
"Pieszyce",
"Pilawa",
"Pilica",
"Pilzno",
"Piła",
"Piława Górna",
"Pińczów",
"Pionki",
"Piotrków Kujawski",
"Piotrków Trybunalski",
"Pisz",
"Piwniczna-Zdrój",
"Pleszew",
"Płock",
"Płońsk",
"Płoty",
"Pniewy",
"Pobiedziska",
"Poddębice",
"Podkowa Leśna",
"Pogorzela",
"Polanica-Zdrój",
"Polanów",
"Police",
"Polkowice",
"Połaniec",
"Połczyn-Zdrój",
"Poniatowa",
"Poniec",
"Poręba",
"Poznań",
"Prabuty",
"Praszka",
"Prochowice",
"Proszowice",
"Prószków",
"Pruchnik",
"Prudnik",
"Prusice",
"Pruszcz Gdański",
"Pruszków",
"Przasnysz",
"Przecław",
"Przedbórz",
"Przedecz",
"Przemków",
"Przemyśl",
"Przeworsk",
"Przysucha",
"Pszczyna",
"Pszów",
"Puck",
"Puławy",
"Pułtusk",
"Puszczykowo",
"Pyrzyce",
"Pyskowice",
"Pyzdry",
"Rabka-Zdrój",
"Raciąż",
"Racibórz",
"Radków",
"Radlin",
"Radłów",
"Radom",
"Radomsko",
"Radomyśl Wielki",
"Radymno",
"Radziejów",
"Radzionków",
"Radzymin",
"Radzyń Chełmiński",
"Radzyń Podlaski",
"Rajgród",
"Rakoniewice",
"Raszków",
"Rawa Mazowiecka",
"Rawicz",
"Recz",
"Reda",
"Rejowiec Fabryczny",
"Resko",
"Reszel",
"Rogoźno",
"Ropczyce",
"Różan",
"Ruciane-Nida",
"Ruda Śląska",
"Rudnik nad Sanem",
"Rumia",
"Rybnik",
"Rychwał",
"Rydułtowy",
"Rydzyna",
"Ryglice",
"Ryki",
"Rymanów",
"Ryn",
"Rypin",
"Rzepin",
"Rzeszów",
"Rzgów",
"Sandomierz",
"Sanok",
"Sejny",
"Serock",
"Sędziszów",
"Sędziszów Małopolski",
"Sępopol",
"Sępólno Krajeńskie",
"Sianów",
"Siechnice",
"Siedlce",
"Siemianowice Śląskie",
"Siemiatycze",
"Sieniawa",
"Sieradz",
"Sieraków",
"Sierpc",
"Siewierz",
"Skalbmierz",
"Skała",
"Skarszewy",
"Skaryszew",
"Skarżysko-Kamienna",
"Skawina",
"Skępe",
"Skierniewice",
"Skoczów",
"Skoki",
"Skórcz",
"Skwierzyna",
"Sława",
"Sławków",
"Sławno",
"Słomniki",
"Słubice",
"Słupca",
"Słupsk",
"Sobótka",
"Sochaczew",
"Sokołów Małopolski",
"Sokołów Podlaski",
"Sokółka",
"Solec Kujawski",
"Sompolno",
"Sopot",
"Sosnowiec",
"Sośnicowice",
"Stalowa Wola",
"Starachowice",
"Stargard Szczeciński",
"Starogard Gdański",
"Stary Sącz",
"Staszów",
"Stawiski",
"Stawiszyn",
"Stąporków",
"Stęszew",
"Stoczek Łukowski",
"Stronie Śląskie",
"Strumień",
"Stryków",
"Strzegom",
"Strzelce Krajeńskie",
"Strzelce Opolskie",
"Strzelin",
"Strzelno",
"Strzyżów",
"Sucha Beskidzka",
"Suchań",
"Suchedniów",
"Suchowola",
"Sulechów",
"Sulejów",
"Sulejówek",
"Sulęcin",
"Sulmierzyce",
"Sułkowice",
"Supraśl",
"Suraż",
"Susz",
"Suwałki",
"Swarzędz",
"Syców",
"Szadek",
"Szamocin",
"Szamotuły",
"Szczawnica",
"Szczawno-Zdrój",
"Szczebrzeszyn",
"Szczecin",
"Szczecinek",
"Szczekociny",
"Szczucin",
"Szczuczyn",
"Szczyrk",
"Szczytna",
"Szczytno",
"Szepietowo",
"Szklarska Poręba",
"Szlichtyngowa",
"Szprotawa",
"Sztum",
"Szubin",
"Szydłowiec",
"Ścinawa",
"Ślesin",
"Śmigiel",
"Śrem",
"Środa Śląska",
"Środa Wielkopolska",
"Świątniki Górne",
"Świdnica",
"Świdnik",
"Świdwin",
"Świebodzice",
"Świebodzin",
"Świecie",
"Świeradów-Zdrój",
"Świerzawa",
"Świętochłowice",
"Świnoujście",
"Tarczyn",
"Tarnobrzeg",
"Tarnogród",
"Tarnowskie Góry",
"Tarnów",
"Tczew",
"Terespol",
"Tłuszcz",
"Tolkmicko",
"Tomaszów Lubelski",
"Tomaszów Mazowiecki",
"Toruń",
"Torzym",
"Toszek",
"Trzcianka",
"Trzciel",
"Trzcińsko-Zdrój",
"Trzebiatów",
"Trzebinia",
"Trzebnica",
"Trzemeszno",
"Tuchola",
"Tuchów",
"Tuczno",
"Tuliszków",
"Turek",
"Tuszyn",
"Twardogóra",
"Tychowo",
"Tychy",
"Tyczyn",
"Tykocin",
"Tyszowce",
"Ujazd",
"Ujście",
"Ulanów",
"Uniejów",
"Ustka",
"Ustroń",
"Ustrzyki Dolne",
"Wadowice",
"Wałbrzych",
"Wałcz",
"Warka",
"Warszawa",
"Warta",
"Wasilków",
"Wąbrzeźno",
"Wąchock",
"Wągrowiec",
"Wąsosz",
"Wejherowo",
"Węgliniec",
"Węgorzewo",
"Węgorzyno",
"Węgrów",
"Wiązów",
"Wieleń",
"Wielichowo",
"Wieliczka",
"Wieluń",
"Wieruszów",
"Więcbork",
"Wilamowice",
"Wisła",
"Witkowo",
"Witnica",
"Wleń",
"Władysławowo",
"Włocławek",
"Włodawa",
"Włoszczowa",
"Wodzisław Śląski",
"Wojcieszów",
"Wojkowice",
"Wojnicz",
"Wolbórz",
"Wolbrom",
"Wolin",
"Wolsztyn",
"Wołczyn",
"Wołomin",
"Wołów",
"Woźniki",
"Wrocław",
"Wronki",
"Września",
"Wschowa",
"Wyrzysk",
"Wysoka",
"Wysokie Mazowieckie",
"Wyszków",
"Wyszogród",
"Wyśmierzyce",
"Zabłudów",
"Zabrze",
"Zagórów",
"Zagórz",
"Zakliczyn",
"Zakopane",
"Zakroczym",
"Zalewo",
"Zambrów",
"Zamość",
"Zator",
"Zawadzkie",
"Zawichost",
"Zawidów",
"Zawiercie",
"Ząbki",
"Ząbkowice Śląskie",
"Zbąszynek",
"Zbąszyń",
"Zduny",
"Zduńska Wola",
"Zdzieszowice",
"Zelów",
"Zgierz",
"Zgorzelec",
"Zielona Góra",
"Zielonka",
"Ziębice",
"Złocieniec",
"Złoczew",
"Złotoryja",
"Złotów",
"Złoty Stok",
"Zwierzyniec",
"Zwoleń",
"Żabno",
"Żagań",
"Żarki",
"Żarów",
"Żary",
"Żelechów",
"Żerków",
"Żmigród",
"Żnin",
"Żory",
"Żukowo",
"Żuromin",
"Żychlin",
"Żyrardów",
"Żywiec"
];
},{}],125:[function(require,module,exports){
module["exports"] = [
"Afganistan",
"Albania",
"Algieria",
"Andora",
"Angola",
"Antigua i Barbuda",
"Arabia Saudyjska",
"Argentyna",
"Armenia",
"Australia",
"Austria",
"Azerbejdżan",
"Bahamy",
"Bahrajn",
"Bangladesz",
"Barbados",
"Belgia",
"Belize",
"Benin",
"Bhutan",
"Białoruś",
"Birma",
"Boliwia",
"Sucre",
"Bośnia i Hercegowina",
"Botswana",
"Brazylia",
"Brunei",
"Bułgaria",
"Burkina Faso",
"Burundi",
"Chile",
"Chiny",
"Chorwacja",
"Cypr",
"Czad",
"Czarnogóra",
"Czechy",
"Dania",
"Demokratyczna Republika Konga",
"Dominika",
"Dominikana",
"Dżibuti",
"Egipt",
"Ekwador",
"Erytrea",
"Estonia",
"Etiopia",
"Fidżi",
"Filipiny",
"Finlandia",
"Francja",
"Gabon",
"Gambia",
"Ghana",
"Grecja",
"Grenada",
"Gruzja",
"Gujana",
"Gwatemala",
"Gwinea",
"Gwinea Bissau",
"Gwinea Równikowa",
"Haiti",
"Hiszpania",
"Holandia",
"Haga",
"Honduras",
"Indie",
"Indonezja",
"Irak",
"Iran",
"Irlandia",
"Islandia",
"Izrael",
"Jamajka",
"Japonia",
"Jemen",
"Jordania",
"Kambodża",
"Kamerun",
"Kanada",
"Katar",
"Kazachstan",
"Kenia",
"Kirgistan",
"Kiribati",
"Kolumbia",
"Komory",
"Kongo",
"Korea Południowa",
"Korea Północna",
"Kostaryka",
"Kuba",
"Kuwejt",
"Laos",
"Lesotho",
"Liban",
"Liberia",
"Libia",
"Liechtenstein",
"Litwa",
"Luksemburg",
"Łotwa",
"Macedonia",
"Madagaskar",
"Malawi",
"Malediwy",
"Malezja",
"Mali",
"Malta",
"Maroko",
"Mauretania",
"Mauritius",
"Meksyk",
"Mikronezja",
"Mołdawia",
"Monako",
"Mongolia",
"Mozambik",
"Namibia",
"Nauru",
"Nepal",
"Niemcy",
"Niger",
"Nigeria",
"Nikaragua",
"Norwegia",
"Nowa Zelandia",
"Oman",
"Pakistan",
"Palau",
"Panama",
"Papua-Nowa Gwinea",
"Paragwaj",
"Peru",
"Polska",
"322 575",
"Portugalia",
"Republika Południowej Afryki",
"Republika Środkowoafrykańska",
"Republika Zielonego Przylądka",
"Rosja",
"Rumunia",
"Rwanda",
"Saint Kitts i Nevis",
"Saint Lucia",
"Saint Vincent i Grenadyny",
"Salwador",
"Samoa",
"San Marino",
"Senegal",
"Serbia",
"Seszele",
"Sierra Leone",
"Singapur",
"Słowacja",
"Słowenia",
"Somalia",
"Sri Lanka",
"Stany Zjednoczone",
"Suazi",
"Sudan",
"Sudan Południowy",
"Surinam",
"Syria",
"Szwajcaria",
"Szwecja",
"Tadżykistan",
"Tajlandia",
"Tanzania",
"Timor Wschodni",
"Togo",
"Tonga",
"Trynidad i Tobago",
"Tunezja",
"Turcja",
"Turkmenistan",
"Tuvalu",
"Funafuti",
"Uganda",
"Ukraina",
"Urugwaj",
2008,
"Uzbekistan",
"Vanuatu",
"Watykan",
"Wenezuela",
"Węgry",
"Wielka Brytania",
"Wietnam",
"Włochy",
"Wybrzeże Kości Słoniowej",
"Wyspy Marshalla",
"Wyspy Salomona",
"Wyspy Świętego Tomasza i Książęca",
"Zambia",
"Zimbabwe",
"Zjednoczone Emiraty Arabskie"
];
},{}],126:[function(require,module,exports){
module["exports"] = [
"Polska"
];
},{}],127:[function(require,module,exports){
var address = {};
module['exports'] = address;
address.country = require("./country");
address.building_number = require("./building_number");
address.street_prefix = require("./street_prefix");
address.secondary_address = require("./secondary_address");
address.postcode = require("./postcode");
address.state = require("./state");
address.state_abbr = require("./state_abbr");
address.city_name = require("./city_name");
address.city = require("./city");
address.street_name = require("./street_name");
address.street_address = require("./street_address");
address.default_country = require("./default_country");
},{"./building_number":122,"./city":123,"./city_name":124,"./country":125,"./default_country":126,"./postcode":128,"./secondary_address":129,"./state":130,"./state_abbr":131,"./street_address":132,"./street_name":133,"./street_prefix":134}],128:[function(require,module,exports){
module["exports"] = [
"##-###"
];
},{}],129:[function(require,module,exports){
arguments[4][48][0].apply(exports,arguments)
},{"dup":48}],130:[function(require,module,exports){
module["exports"] = [
"Dolnośląskie",
"Kujawsko-pomorskie",
"Lubelskie",
"Lubuskie",
"Łódzkie",
"Małopolskie",
"Mazowieckie",
"Opolskie",
"Podkarpackie",
"Podlaskie",
"Pomorskie",
"Śląskie",
"Świętokrzyskie",
"Warmińsko-mazurskie",
"Wielkopolskie",
"Zachodniopomorskie"
];
},{}],131:[function(require,module,exports){
module["exports"] = [
"DŚ",
"KP",
"LB",
"LS",
"ŁD",
"MP",
"MZ",
"OP",
"PK",
"PL",
"PM",
"ŚL",
"ŚK",
"WM",
"WP",
"ZP"
];
},{}],132:[function(require,module,exports){
module["exports"] = [
"#{street_name} #{building_number}"
];
},{}],133:[function(require,module,exports){
module["exports"] = [
"#{street_prefix} #{Name.last_name}"
];
},{}],134:[function(require,module,exports){
module["exports"] = [
"ul.",
"al."
];
},{}],135:[function(require,module,exports){
module["exports"] = [
"50-###-##-##",
"51-###-##-##",
"53-###-##-##",
"57-###-##-##",
"60-###-##-##",
"66-###-##-##",
"69-###-##-##",
"72-###-##-##",
"73-###-##-##",
"78-###-##-##",
"79-###-##-##",
"88-###-##-##"
];
},{}],136:[function(require,module,exports){
arguments[4][64][0].apply(exports,arguments)
},{"./formats":135,"dup":64}],137:[function(require,module,exports){
arguments[4][69][0].apply(exports,arguments)
},{"dup":69}],138:[function(require,module,exports){
arguments[4][70][0].apply(exports,arguments)
},{"dup":70}],139:[function(require,module,exports){
arguments[4][71][0].apply(exports,arguments)
},{"dup":71}],140:[function(require,module,exports){
arguments[4][72][0].apply(exports,arguments)
},{"dup":72}],141:[function(require,module,exports){
arguments[4][73][0].apply(exports,arguments)
},{"dup":73}],142:[function(require,module,exports){
var company = {};
module['exports'] = company;
company.suffix = require("./suffix");
company.adjetive = require("./adjetive");
company.descriptor = require("./descriptor");
company.noun = require("./noun");
company.bs_verb = require("./bs_verb");
company.bs_adjective = require("./bs_adjective");
company.bs_noun = require("./bs_noun");
company.name = require("./name");
},{"./adjetive":137,"./bs_adjective":138,"./bs_noun":139,"./bs_verb":140,"./descriptor":141,"./name":143,"./noun":144,"./suffix":145}],143:[function(require,module,exports){
arguments[4][75][0].apply(exports,arguments)
},{"dup":75}],144:[function(require,module,exports){
arguments[4][76][0].apply(exports,arguments)
},{"dup":76}],145:[function(require,module,exports){
arguments[4][77][0].apply(exports,arguments)
},{"dup":77}],146:[function(require,module,exports){
var pl = {};
module['exports'] = pl;
pl.title = "Polish";
pl.name = require("./name");
pl.address = require("./address");
pl.company = require("./company");
pl.internet = require("./internet");
pl.lorem = require("./lorem");
pl.phone_number = require("./phone_number");
pl.cell_phone = require("./cell_phone");
},{"./address":127,"./cell_phone":136,"./company":142,"./internet":149,"./lorem":150,"./name":154,"./phone_number":160}],147:[function(require,module,exports){
module["exports"] = [
"com",
"pl",
"com.pl",
"net",
"org"
];
},{}],148:[function(require,module,exports){
arguments[4][105][0].apply(exports,arguments)
},{"dup":105}],149:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.free_email = require("./free_email");
internet.domain_suffix = require("./domain_suffix");
},{"./domain_suffix":147,"./free_email":148}],150:[function(require,module,exports){
arguments[4][107][0].apply(exports,arguments)
},{"./supplemental":151,"./words":152,"dup":107}],151:[function(require,module,exports){
arguments[4][108][0].apply(exports,arguments)
},{"dup":108}],152:[function(require,module,exports){
arguments[4][109][0].apply(exports,arguments)
},{"dup":109}],153:[function(require,module,exports){
module["exports"] = [
"Aaron",
"Abraham",
"Adam",
"Adrian",
"Atanazy",
"Agaton",
"Alan",
"Albert",
"Aleksander",
"Aleksy",
"Alfred",
"Alwar",
"Ambroży",
"Anatol",
"Andrzej",
"Antoni",
"Apollinary",
"Apollo",
"Arkady",
"Arkadiusz",
"Archibald",
"Arystarch",
"Arnold",
"Arseniusz",
"Artur",
"August",
"Baldwin",
"Bazyli",
"Benedykt",
"Beniamin",
"Bernard",
"Bertrand",
"Bertram",
"Borys",
"Brajan",
"Bruno",
"Cezary",
"Cecyliusz",
"Karol",
"Krystian",
"Krzysztof",
"Klarencjusz",
"Klaudiusz",
"Klemens",
"Konrad",
"Konstanty",
"Konstantyn",
"Kornel",
"Korneliusz",
"Korneli",
"Cyryl",
"Cyrus",
"Damian",
"Daniel",
"Dariusz",
"Dawid",
"Dionizy",
"Demetriusz",
"Dominik",
"Donald",
"Dorian",
"Edgar",
"Edmund",
"Edward",
"Edwin",
"Efrem",
"Efraim",
"Eliasz",
"Eleazar",
"Emil",
"Emanuel",
"Erast",
"Ernest",
"Eugeniusz",
"Eustracjusz",
"Fabian",
"Feliks",
"Florian",
"Franciszek",
"Fryderyk",
"Gabriel",
"Gedeon",
"Galfryd",
"Jerzy",
"Gerald",
"Gerazym",
"Gilbert",
"Gonsalwy",
"Grzegorz",
"Gwido",
"Harald",
"Henryk",
"Herbert",
"Herman",
"Hilary",
"Horacy",
"Hubert",
"Hugo",
"Ignacy",
"Igor",
"Hilarion",
"Innocenty",
"Hipolit",
"Ireneusz",
"Erwin",
"Izaak",
"Izajasz",
"Izydor",
"Jakub",
"Jeremi",
"Jeremiasz",
"Hieronim",
"Gerald",
"Joachim",
"Jan",
"Janusz",
"Jonatan",
"Józef",
"Jozue",
"Julian",
"Juliusz",
"Justyn",
"Kalistrat",
"Kazimierz",
"Wawrzyniec",
"Laurenty",
"Laurencjusz",
"Łazarz",
"Leon",
"Leonard",
"Leonid",
"Leon",
"Ludwik",
"Łukasz",
"Lucjan",
"Magnus",
"Makary",
"Marceli",
"Marek",
"Marcin",
"Mateusz",
"Maurycy",
"Maksym",
"Maksymilian",
"Michał",
"Miron",
"Modest",
"Mojżesz",
"Natan",
"Natanael",
"Nazariusz",
"Nazary",
"Nestor",
"Mikołaj",
"Nikodem",
"Olaf",
"Oleg",
"Oliwier",
"Onufry",
"Orestes",
"Oskar",
"Ansgary",
"Osmund",
"Pankracy",
"Pantaleon",
"Patryk",
"Patrycjusz",
"Patrycy",
"Paweł",
"Piotr",
"Filemon",
"Filip",
"Platon",
"Polikarp",
"Porfiry",
"Porfiriusz",
"Prokles",
"Prokul",
"Prokop",
"Kwintyn",
"Randolf",
"Rafał",
"Rajmund",
"Reginald",
"Rajnold",
"Ryszard",
"Robert",
"Roderyk",
"Roger",
"Roland",
"Roman",
"Romeo",
"Reginald",
"Rudolf",
"Samson",
"Samuel",
"Salwator",
"Sebastian",
"Serafin",
"Sergiusz",
"Seweryn",
"Zygmunt",
"Sylwester",
"Szymon",
"Salomon",
"Spirydion",
"Stanisław",
"Szczepan",
"Stefan",
"Terencjusz",
"Teodor",
"Tomasz",
"Tymoteusz",
"Tobiasz",
"Walenty",
"Walentyn",
"Walerian",
"Walery",
"Wiktor",
"Wincenty",
"Witalis",
"Włodzimierz",
"Władysław",
"Błażej",
"Walter",
"Walgierz",
"Wacław",
"Wilfryd",
"Wilhelm",
"Ksawery",
"Ksenofont",
"Jerzy",
"Zachariasz",
"Zachary",
"Ada",
"Adelajda",
"Agata",
"Agnieszka",
"Agrypina",
"Aida",
"Aleksandra",
"Alicja",
"Alina",
"Amanda",
"Anastazja",
"Angela",
"Andżelika",
"Angelina",
"Anna",
"Hanna",
"—",
"Antonina",
"Ariadna",
"Aurora",
"Barbara",
"Beatrycze",
"Berta",
"Brygida",
"Kamila",
"Karolina",
"Karolina",
"Kornelia",
"Katarzyna",
"Cecylia",
"Karolina",
"Chloe",
"Krystyna",
"Klara",
"Klaudia",
"Klementyna",
"Konstancja",
"Koralia",
"Daria",
"Diana",
"Dina",
"Dorota",
"Edyta",
"Eleonora",
"Eliza",
"Elżbieta",
"Izabela",
"Elwira",
"Emilia",
"Estera",
"Eudoksja",
"Eudokia",
"Eugenia",
"Ewa",
"Ewelina",
"Ferdynanda",
"Florencja",
"Franciszka",
"Gabriela",
"Gertruda",
"Gloria",
"Gracja",
"Jadwiga",
"Helena",
"Henryka",
"Nadzieja",
"Ida",
"Ilona",
"Helena",
"Irena",
"Irma",
"Izabela",
"Izolda",
"Jakubina",
"Joanna",
"Janina",
"Żaneta",
"Joanna",
"Ginewra",
"Józefina",
"Judyta",
"Julia",
"Julia",
"Julita",
"Justyna",
"Kira",
"Cyra",
"Kleopatra",
"Larysa",
"Laura",
"Laurencja",
"Laurentyna",
"Lea",
"Leila",
"Eleonora",
"Liliana",
"Lilianna",
"Lilia",
"Lilla",
"Liza",
"Eliza",
"Laura",
"Ludwika",
"Luiza",
"Łucja",
"Lucja",
"Lidia",
"Amabela",
"Magdalena",
"Malwina",
"Małgorzata",
"Greta",
"Marianna",
"Maryna",
"Marta",
"Martyna",
"Maria",
"Matylda",
"Maja",
"Maja",
"Melania",
"Michalina",
"Monika",
"Nadzieja",
"Noemi",
"Natalia",
"Nikola",
"Nina",
"Olga",
"Olimpia",
"Oliwia",
"Ofelia",
"Patrycja",
"Paula",
"Pelagia",
"Penelopa",
"Filipa",
"Paulina",
"Rachela",
"Rebeka",
"Regina",
"Renata",
"Rozalia",
"Róża",
"Roksana",
"Rufina",
"Ruta",
"Sabina",
"Sara",
"Serafina",
"Sybilla",
"Sylwia",
"Zofia",
"Stella",
"Stefania",
"Zuzanna",
"Tamara",
"Tacjana",
"Tekla",
"Teodora",
"Teresa",
"Walentyna",
"Waleria",
"Wanesa",
"Wiara",
"Weronika",
"Wiktoria",
"Wirginia",
"Bibiana",
"Bibianna",
"Wanda",
"Wilhelmina",
"Ksawera",
"Ksenia",
"Zoe"
];
},{}],154:[function(require,module,exports){
var name = {};
module['exports'] = name;
name.first_name = require("./first_name");
name.last_name = require("./last_name");
name.prefix = require("./prefix");
name.title = require("./title");
name.name = require("./name");
},{"./first_name":153,"./last_name":155,"./name":156,"./prefix":157,"./title":158}],155:[function(require,module,exports){
module["exports"] = [
"Adamczak",
"Adamczyk",
"Adamek",
"Adamiak",
"Adamiec",
"Adamowicz",
"Adamski",
"Adamus",
"Aleksandrowicz",
"Andrzejczak",
"Andrzejewski",
"Antczak",
"Augustyn",
"Augustyniak",
"Bagiński",
"Balcerzak",
"Banach",
"Banasiak",
"Banasik",
"Banaś",
"Baran",
"Baranowski",
"Barański",
"Bartczak",
"Bartkowiak",
"Bartnik",
"Bartosik",
"Bednarczyk",
"Bednarek",
"Bednarski",
"Bednarz",
"Białas",
"Białek",
"Białkowski",
"Bielak",
"Bielawski",
"Bielecki",
"Bielski",
"Bieniek",
"Biernacki",
"Biernat",
"Bieńkowski",
"Bilski",
"Bober",
"Bochenek",
"Bogucki",
"Bogusz",
"Borek",
"Borkowski",
"Borowiec",
"Borowski",
"Bożek",
"Broda",
"Brzeziński",
"Brzozowski",
"Buczek",
"Buczkowski",
"Buczyński",
"Budziński",
"Budzyński",
"Bujak",
"Bukowski",
"Burzyński",
"Bąk",
"Bąkowski",
"Błaszczak",
"Błaszczyk",
"Cebula",
"Chmiel",
"Chmielewski",
"Chmura",
"Chojnacki",
"Chojnowski",
"Cholewa",
"Chrzanowski",
"Chudzik",
"Cichocki",
"Cichoń",
"Cichy",
"Ciesielski",
"Cieśla",
"Cieślak",
"Cieślik",
"Ciszewski",
"Cybulski",
"Cygan",
"Czaja",
"Czajka",
"Czajkowski",
"Czapla",
"Czarnecki",
"Czech",
"Czechowski",
"Czekaj",
"Czerniak",
"Czerwiński",
"Czyż",
"Czyżewski",
"Dec",
"Dobosz",
"Dobrowolski",
"Dobrzyński",
"Domagała",
"Domański",
"Dominiak",
"Drabik",
"Drozd",
"Drozdowski",
"Drzewiecki",
"Dróżdż",
"Dubiel",
"Duda",
"Dudek",
"Dudziak",
"Dudzik",
"Dudziński",
"Duszyński",
"Dziedzic",
"Dziuba",
"Dąbek",
"Dąbkowski",
"Dąbrowski",
"Dębowski",
"Dębski",
"Długosz",
"Falkowski",
"Fijałkowski",
"Filipek",
"Filipiak",
"Filipowicz",
"Flak",
"Flis",
"Florczak",
"Florek",
"Frankowski",
"Frąckowiak",
"Frączek",
"Frątczak",
"Furman",
"Gadomski",
"Gajda",
"Gajewski",
"Gaweł",
"Gawlik",
"Gawron",
"Gawroński",
"Gałka",
"Gałązka",
"Gil",
"Godlewski",
"Golec",
"Gołąb",
"Gołębiewski",
"Gołębiowski",
"Grabowski",
"Graczyk",
"Grochowski",
"Grudzień",
"Gruszczyński",
"Gruszka",
"Grzegorczyk",
"Grzelak",
"Grzesiak",
"Grzesik",
"Grześkowiak",
"Grzyb",
"Grzybowski",
"Grzywacz",
"Gutowski",
"Guzik",
"Gwóźdź",
"Góra",
"Góral",
"Górecki",
"Górka",
"Górniak",
"Górny",
"Górski",
"Gąsior",
"Gąsiorowski",
"Głogowski",
"Głowacki",
"Głąb",
"Hajduk",
"Herman",
"Iwański",
"Izdebski",
"Jabłoński",
"Jackowski",
"Jagielski",
"Jagiełło",
"Jagodziński",
"Jakubiak",
"Jakubowski",
"Janas",
"Janiak",
"Janicki",
"Janik",
"Janiszewski",
"Jankowiak",
"Jankowski",
"Janowski",
"Janus",
"Janusz",
"Januszewski",
"Jaros",
"Jarosz",
"Jarząbek",
"Jasiński",
"Jastrzębski",
"Jaworski",
"Jaśkiewicz",
"Jezierski",
"Jurek",
"Jurkiewicz",
"Jurkowski",
"Juszczak",
"Jóźwiak",
"Jóźwik",
"Jędrzejczak",
"Jędrzejczyk",
"Jędrzejewski",
"Kacprzak",
"Kaczmarczyk",
"Kaczmarek",
"Kaczmarski",
"Kaczor",
"Kaczorowski",
"Kaczyński",
"Kaleta",
"Kalinowski",
"Kalisz",
"Kamiński",
"Kania",
"Kaniewski",
"Kapusta",
"Karaś",
"Karczewski",
"Karpiński",
"Karwowski",
"Kasperek",
"Kasprzak",
"Kasprzyk",
"Kaszuba",
"Kawa",
"Kawecki",
"Kałuża",
"Kaźmierczak",
"Kiełbasa",
"Kisiel",
"Kita",
"Klimczak",
"Klimek",
"Kmiecik",
"Kmieć",
"Knapik",
"Kobus",
"Kogut",
"Kolasa",
"Komorowski",
"Konieczna",
"Konieczny",
"Konopka",
"Kopczyński",
"Koper",
"Kopeć",
"Korzeniowski",
"Kos",
"Kosiński",
"Kosowski",
"Kostecki",
"Kostrzewa",
"Kot",
"Kotowski",
"Kowal",
"Kowalczuk",
"Kowalczyk",
"Kowalewski",
"Kowalik",
"Kowalski",
"Koza",
"Kozak",
"Kozieł",
"Kozioł",
"Kozłowski",
"Kołakowski",
"Kołodziej",
"Kołodziejczyk",
"Kołodziejski",
"Krajewski",
"Krakowiak",
"Krawczyk",
"Krawiec",
"Kruk",
"Krukowski",
"Krupa",
"Krupiński",
"Kruszewski",
"Krysiak",
"Krzemiński",
"Krzyżanowski",
"Król",
"Królikowski",
"Książek",
"Kubacki",
"Kubiak",
"Kubica",
"Kubicki",
"Kubik",
"Kuc",
"Kucharczyk",
"Kucharski",
"Kuchta",
"Kuciński",
"Kuczyński",
"Kujawa",
"Kujawski",
"Kula",
"Kulesza",
"Kulig",
"Kulik",
"Kuliński",
"Kurek",
"Kurowski",
"Kuś",
"Kwaśniewski",
"Kwiatkowski",
"Kwiecień",
"Kwieciński",
"Kędzierski",
"Kędziora",
"Kępa",
"Kłos",
"Kłosowski",
"Lach",
"Laskowski",
"Lasota",
"Lech",
"Lenart",
"Lesiak",
"Leszczyński",
"Lewandowski",
"Lewicki",
"Leśniak",
"Leśniewski",
"Lipiński",
"Lipka",
"Lipski",
"Lis",
"Lisiecki",
"Lisowski",
"Maciejewski",
"Maciąg",
"Mackiewicz",
"Madej",
"Maj",
"Majcher",
"Majchrzak",
"Majewski",
"Majka",
"Makowski",
"Malec",
"Malicki",
"Malinowski",
"Maliszewski",
"Marchewka",
"Marciniak",
"Marcinkowski",
"Marczak",
"Marek",
"Markiewicz",
"Markowski",
"Marszałek",
"Marzec",
"Masłowski",
"Matusiak",
"Matuszak",
"Matuszewski",
"Matysiak",
"Mazur",
"Mazurek",
"Mazurkiewicz",
"Maćkowiak",
"Małecki",
"Małek",
"Maślanka",
"Michalak",
"Michalczyk",
"Michalik",
"Michalski",
"Michałek",
"Michałowski",
"Mielczarek",
"Mierzejewski",
"Mika",
"Mikołajczak",
"Mikołajczyk",
"Mikulski",
"Milczarek",
"Milewski",
"Miller",
"Misiak",
"Misztal",
"Miśkiewicz",
"Modzelewski",
"Molenda",
"Morawski",
"Motyka",
"Mroczek",
"Mroczkowski",
"Mrozek",
"Mróz",
"Mucha",
"Murawski",
"Musiał",
"Muszyński",
"Młynarczyk",
"Napierała",
"Nawrocki",
"Nawrot",
"Niedziela",
"Niedzielski",
"Niedźwiecki",
"Niemczyk",
"Niemiec",
"Niewiadomski",
"Noga",
"Nowacki",
"Nowaczyk",
"Nowak",
"Nowakowski",
"Nowicki",
"Nowiński",
"Olczak",
"Olejniczak",
"Olejnik",
"Olszewski",
"Orzechowski",
"Orłowski",
"Osiński",
"Ossowski",
"Ostrowski",
"Owczarek",
"Paczkowski",
"Pająk",
"Pakuła",
"Paluch",
"Panek",
"Partyka",
"Pasternak",
"Paszkowski",
"Pawelec",
"Pawlak",
"Pawlicki",
"Pawlik",
"Pawlikowski",
"Pawłowski",
"Pałka",
"Piasecki",
"Piechota",
"Piekarski",
"Pietras",
"Pietruszka",
"Pietrzak",
"Pietrzyk",
"Pilarski",
"Pilch",
"Piotrowicz",
"Piotrowski",
"Piwowarczyk",
"Piórkowski",
"Piątek",
"Piątkowski",
"Piłat",
"Pluta",
"Podgórski",
"Polak",
"Popławski",
"Porębski",
"Prokop",
"Prus",
"Przybylski",
"Przybysz",
"Przybył",
"Przybyła",
"Ptak",
"Puchalski",
"Pytel",
"Płonka",
"Raczyński",
"Radecki",
"Radomski",
"Rak",
"Rakowski",
"Ratajczak",
"Robak",
"Rogala",
"Rogalski",
"Rogowski",
"Rojek",
"Romanowski",
"Rosa",
"Rosiak",
"Rosiński",
"Ruciński",
"Rudnicki",
"Rudziński",
"Rudzki",
"Rusin",
"Rutkowski",
"Rybak",
"Rybarczyk",
"Rybicki",
"Rzepka",
"Różański",
"Różycki",
"Sadowski",
"Sawicki",
"Serafin",
"Siedlecki",
"Sienkiewicz",
"Sieradzki",
"Sikora",
"Sikorski",
"Sitek",
"Siwek",
"Skalski",
"Skiba",
"Skibiński",
"Skoczylas",
"Skowron",
"Skowronek",
"Skowroński",
"Skrzypczak",
"Skrzypek",
"Skóra",
"Smoliński",
"Sobczak",
"Sobczyk",
"Sobieraj",
"Sobolewski",
"Socha",
"Sochacki",
"Sokołowski",
"Sokół",
"Sosnowski",
"Sowa",
"Sowiński",
"Sołtys",
"Sołtysiak",
"Sroka",
"Stachowiak",
"Stachowicz",
"Stachura",
"Stachurski",
"Stanek",
"Staniszewski",
"Stanisławski",
"Stankiewicz",
"Stasiak",
"Staszewski",
"Stawicki",
"Stec",
"Stefaniak",
"Stefański",
"Stelmach",
"Stolarczyk",
"Stolarski",
"Strzelczyk",
"Strzelecki",
"Stępień",
"Stępniak",
"Surma",
"Suski",
"Szafrański",
"Szatkowski",
"Szczepaniak",
"Szczepanik",
"Szczepański",
"Szczerba",
"Szcześniak",
"Szczygieł",
"Szczęsna",
"Szczęsny",
"Szeląg",
"Szewczyk",
"Szostak",
"Szulc",
"Szwarc",
"Szwed",
"Szydłowski",
"Szymański",
"Szymczak",
"Szymczyk",
"Szymkowiak",
"Szyszka",
"Sławiński",
"Słowik",
"Słowiński",
"Tarnowski",
"Tkaczyk",
"Tokarski",
"Tomala",
"Tomaszewski",
"Tomczak",
"Tomczyk",
"Tracz",
"Trojanowski",
"Trzciński",
"Trzeciak",
"Turek",
"Twardowski",
"Urban",
"Urbanek",
"Urbaniak",
"Urbanowicz",
"Urbańczyk",
"Urbański",
"Walczak",
"Walkowiak",
"Warchoł",
"Wasiak",
"Wasilewski",
"Wawrzyniak",
"Wesołowski",
"Wieczorek",
"Wierzbicki",
"Wilczek",
"Wilczyński",
"Wilk",
"Winiarski",
"Witczak",
"Witek",
"Witkowski",
"Wiącek",
"Więcek",
"Więckowski",
"Wiśniewski",
"Wnuk",
"Wojciechowski",
"Wojtas",
"Wojtasik",
"Wojtczak",
"Wojtkowiak",
"Wolak",
"Woliński",
"Wolny",
"Wolski",
"Woś",
"Woźniak",
"Wrona",
"Wroński",
"Wróbel",
"Wróblewski",
"Wypych",
"Wysocki",
"Wyszyński",
"Wójcicki",
"Wójcik",
"Wójtowicz",
"Wąsik",
"Węgrzyn",
"Włodarczyk",
"Włodarski",
"Zaborowski",
"Zabłocki",
"Zagórski",
"Zając",
"Zajączkowski",
"Zakrzewski",
"Zalewski",
"Zaremba",
"Zarzycki",
"Zaręba",
"Zawada",
"Zawadzki",
"Zdunek",
"Zieliński",
"Zielonka",
"Ziółkowski",
"Zięba",
"Ziętek",
"Zwoliński",
"Zych",
"Zygmunt",
"Łapiński",
"Łuczak",
"Łukasiewicz",
"Łukasik",
"Łukaszewski",
"Śliwa",
"Śliwiński",
"Ślusarczyk",
"Świderski",
"Świerczyński",
"Świątek",
"Żak",
"Żebrowski",
"Żmuda",
"Żuk",
"Żukowski",
"Żurawski",
"Żurek",
"Żyła"
];
},{}],156:[function(require,module,exports){
module["exports"] = [
"#{prefix} #{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}"
];
},{}],157:[function(require,module,exports){
module["exports"] = [
"Pan",
"Pani"
];
},{}],158:[function(require,module,exports){
arguments[4][116][0].apply(exports,arguments)
},{"dup":116}],159:[function(require,module,exports){
module["exports"] = [
"12-###-##-##",
"13-###-##-##",
"14-###-##-##",
"15-###-##-##",
"16-###-##-##",
"17-###-##-##",
"18-###-##-##",
"22-###-##-##",
"23-###-##-##",
"24-###-##-##",
"25-###-##-##",
"29-###-##-##",
"32-###-##-##",
"33-###-##-##",
"34-###-##-##",
"41-###-##-##",
"42-###-##-##",
"43-###-##-##",
"44-###-##-##",
"46-###-##-##",
"48-###-##-##",
"52-###-##-##",
"54-###-##-##",
"55-###-##-##",
"56-###-##-##",
"58-###-##-##",
"59-###-##-##",
"61-###-##-##",
"62-###-##-##",
"63-###-##-##",
"65-###-##-##",
"67-###-##-##",
"68-###-##-##",
"71-###-##-##",
"74-###-##-##",
"75-###-##-##",
"76-###-##-##",
"77-###-##-##",
"81-###-##-##",
"82-###-##-##",
"83-###-##-##",
"84-###-##-##",
"85-###-##-##",
"86-###-##-##",
"87-###-##-##",
"89-###-##-##",
"91-###-##-##",
"94-###-##-##",
"95-###-##-##"
];
},{}],160:[function(require,module,exports){
arguments[4][118][0].apply(exports,arguments)
},{"./formats":159,"dup":118}],161:[function(require,module,exports){
var Lorem = function (faker) {
var self = this;
var Helpers = faker.helpers;
self.words = function (num) {
if (typeof num == 'undefined') { num = 3; }
return Helpers.shuffle(faker.definitions.lorem.words).slice(0, num);
};
self.sentence = function (wordCount, range) {
if (typeof wordCount == 'undefined') { wordCount = 3; }
if (typeof range == 'undefined') { range = 7; }
// strange issue with the node_min_test failing for captialize, please fix and add faker.lorem.back
//return faker.lorem.words(wordCount + Helpers.randomNumber(range)).join(' ').capitalize();
var sentence = faker.lorem.words(wordCount + faker.random.number(range)).join(' ');
return sentence.charAt(0).toUpperCase() + sentence.slice(1) + '.';
};
self.sentences = function (sentenceCount) {
if (typeof sentenceCount == 'undefined') { sentenceCount = 3; }
var sentences = [];
for (sentenceCount; sentenceCount > 0; sentenceCount--) {
sentences.push(faker.lorem.sentence());
}
return sentences.join("\n");
};
self.paragraph = function (sentenceCount) {
if (typeof sentenceCount == 'undefined') { sentenceCount = 3; }
return faker.lorem.sentences(sentenceCount + faker.random.number(3));
};
self.paragraphs = function (paragraphCount, separator) {
if (typeof separator === "undefined") {
separator = "\n \r";
}
if (typeof paragraphCount == 'undefined') { paragraphCount = 3; }
var paragraphs = [];
for (paragraphCount; paragraphCount > 0; paragraphCount--) {
paragraphs.push(faker.lorem.paragraph());
}
return paragraphs.join(separator);
}
return self;
};
module["exports"] = Lorem;
},{}],162:[function(require,module,exports){
function Name (faker) {
this.firstName = function (gender) {
if (typeof faker.definitions.name.male_first_name !== "undefined" && typeof faker.definitions.name.female_first_name !== "undefined") {
// some locale datasets ( like ru ) have first_name split by gender. since the name.first_name field does not exist in these datasets,
// we must randomly pick a name from either gender array so faker.name.firstName will return the correct locale data ( and not fallback )
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_first_name)
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_first_name);
}
}
return faker.random.arrayElement(faker.definitions.name.first_name);
};
this.lastName = function (gender) {
if (typeof faker.definitions.name.male_last_name !== "undefined" && typeof faker.definitions.name.female_last_name !== "undefined") {
// some locale datasets ( like ru ) have last_name split by gender. i have no idea how last names can have genders, but also i do not speak russian
// see above comment of firstName method
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_last_name);
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_last_name);
}
}
return faker.random.arrayElement(faker.definitions.name.last_name);
};
this.findName = function (firstName, lastName, gender) {
var r = faker.random.number(8);
var prefix, suffix;
// in particular locales first and last names split by gender,
// thus we keep consistency by passing 0 as male and 1 as female
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
firstName = firstName || faker.name.firstName(gender);
lastName = lastName || faker.name.lastName(gender);
switch (r) {
case 0:
prefix = faker.name.prefix();
if (prefix) {
return prefix + " " + firstName + " " + lastName;
}
case 1:
suffix = faker.name.prefix();
if (suffix) {
return firstName + " " + lastName + " " + suffix;
}
}
return firstName + " " + lastName;
};
this.jobTitle = function () {
return faker.name.jobDescriptor() + " " +
faker.name.jobArea() + " " +
faker.name.jobType();
};
this.prefix = function () {
return faker.random.arrayElement(faker.definitions.name.prefix);
};
this.suffix = function () {
return faker.random.arrayElement(faker.definitions.name.suffix);
};
this.title = function() {
var descriptor = faker.random.arrayElement(faker.definitions.name.title.descriptor),
level = faker.random.arrayElement(faker.definitions.name.title.level),
job = faker.random.arrayElement(faker.definitions.name.title.job);
return descriptor + " " + level + " " + job;
};
this.jobDescriptor = function () {
return faker.random.arrayElement(faker.definitions.name.title.descriptor);
};
this.jobArea = function () {
return faker.random.arrayElement(faker.definitions.name.title.level);
};
this.jobType = function () {
return faker.random.arrayElement(faker.definitions.name.title.job);
};
}
module['exports'] = Name;
},{}],163:[function(require,module,exports){
var Phone = function (faker) {
var self = this;
self.phoneNumber = function (format) {
format = format || faker.phone.phoneFormats();
return faker.helpers.replaceSymbolWithNumber(format);
};
// FIXME: this is strange passing in an array index.
self.phoneNumberFormat = function (phoneFormatsArrayIndex) {
phoneFormatsArrayIndex = phoneFormatsArrayIndex || 0;
return faker.helpers.replaceSymbolWithNumber(faker.definitions.phone_number.formats[phoneFormatsArrayIndex]);
};
self.phoneFormats = function () {
return faker.random.arrayElement(faker.definitions.phone_number.formats);
};
return self;
};
module['exports'] = Phone;
},{}],164:[function(require,module,exports){
var mersenne = require('../vendor/mersenne');
function Random (faker, seed) {
// Use a user provided seed if it exists
if (seed) {
if (Array.isArray(seed) && seed.length) {
mersenne.seed_array(seed);
}
else {
mersenne.seed(seed);
}
}
// returns a single random number based on a max number or range
this.number = function (options) {
if (typeof options === "number") {
options = {
max: options
};
}
options = options || {};
if (typeof options.min === "undefined") {
options.min = 0;
}
if (typeof options.max === "undefined") {
options.max = 99999;
}
if (typeof options.precision === "undefined") {
options.precision = 1;
}
// Make the range inclusive of the max value
var max = options.max;
if (max >= 0) {
max += options.precision;
}
var randomNumber = options.precision * Math.floor(
mersenne.rand(max / options.precision, options.min / options.precision));
return randomNumber;
}
// takes an array and returns a random element of the array
this.arrayElement = function (array) {
array = array || ["a", "b", "c"];
var r = faker.random.number({ max: array.length - 1 });
return array[r];
}
// takes an object and returns the randomly key or value
this.objectElement = function (object, field) {
object = object || { "foo": "bar", "too": "car" };
var array = Object.keys(object);
var key = faker.random.arrayElement(array);
return field === "key" ? key : object[key];
}
this.uuid = function () {
var RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
var replacePlaceholders = function (placeholder) {
var random = Math.random()*16|0;
var value = placeholder == 'x' ? random : (random &0x3 | 0x8);
return value.toString(16);
};
return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
}
this.boolean =function () {
return !!faker.random.number(1)
}
return this;
}
module['exports'] = Random;
// module.exports = random;
},{"../vendor/mersenne":166}],165:[function(require,module,exports){
var Faker = require('../lib');
var faker = new Faker({ locale: 'pl', localeFallback: 'en' });
faker.locales['pl'] = require('../lib/locales/pl');
faker.locales['en'] = require('../lib/locales/en');
module['exports'] = faker;
},{"../lib":35,"../lib/locales/en":102,"../lib/locales/pl":146}],166:[function(require,module,exports){
// this program is a JavaScript version of Mersenne Twister, with concealment and encapsulation in class,
// an almost straight conversion from the original program, mt19937ar.c,
// translated by y. okada on July 17, 2006.
// and modified a little at july 20, 2006, but there are not any substantial differences.
// in this program, procedure descriptions and comments of original source code were not removed.
// lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions.
// lines commented with /* and */ are original comments.
// lines commented with // are additional comments in this JavaScript version.
// before using this version, create at least one instance of MersenneTwister19937 class, and initialize the each state, given below in c comments, of all the instances.
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
function MersenneTwister19937()
{
/* constants should be scoped inside the class */
var N, M, MATRIX_A, UPPER_MASK, LOWER_MASK;
/* Period parameters */
//c//#define N 624
//c//#define M 397
//c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */
//c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
//c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
N = 624;
M = 397;
MATRIX_A = 0x9908b0df; /* constant vector a */
UPPER_MASK = 0x80000000; /* most significant w-r bits */
LOWER_MASK = 0x7fffffff; /* least significant r bits */
//c//static unsigned long mt[N]; /* the array for the state vector */
//c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
var mt = new Array(N); /* the array for the state vector */
var mti = N+1; /* mti==N+1 means mt[N] is not initialized */
function unsigned32 (n1) // returns a 32-bits unsiged integer from an operand to which applied a bit operator.
{
return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1;
}
function subtraction32 (n1, n2) // emulates lowerflow of a c 32-bits unsiged integer variable, instead of the operator -. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) : n1 - n2;
}
function addition32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator +. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return unsigned32((n1 + n2) & 0xffffffff)
}
function multiplication32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator *. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
var sum = 0;
for (var i = 0; i < 32; ++i){
if ((n1 >>> i) & 0x1){
sum = addition32(sum, unsigned32(n2 << i));
}
}
return sum;
}
/* initializes mt[N] with a seed */
//c//void init_genrand(unsigned long s)
this.init_genrand = function (s)
{
//c//mt[0]= s & 0xffffffff;
mt[0]= unsigned32(s & 0xffffffff);
for (mti=1; mti<N; mti++) {
mt[mti] =
//c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
addition32(multiplication32(1812433253, unsigned32(mt[mti-1] ^ (mt[mti-1] >>> 30))), mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//c//mt[mti] &= 0xffffffff;
mt[mti] = unsigned32(mt[mti] & 0xffffffff);
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
//c//void init_by_array(unsigned long init_key[], int key_length)
this.init_by_array = function (init_key, key_length)
{
//c//int i, j, k;
var i, j, k;
//c//init_genrand(19650218);
this.init_genrand(19650218);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))
//c// + init_key[j] + j; /* non linear */
mt[i] = addition32(addition32(unsigned32(mt[i] ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1664525)), init_key[j]), j);
mt[i] =
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
unsigned32(mt[i] & 0xffffffff);
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))
//c//- i; /* non linear */
mt[i] = subtraction32(unsigned32((dbg=mt[i]) ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1566083941)), i);
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
mt[i] = unsigned32(mt[i] & 0xffffffff);
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
}
/* moved outside of genrand_int32() by jwatte 2010-11-17; generate less garbage */
var mag01 = [0x0, MATRIX_A];
/* generates a random number on [0,0xffffffff]-interval */
//c//unsigned long genrand_int32(void)
this.genrand_int32 = function ()
{
//c//unsigned long y;
//c//static unsigned long mag01[2]={0x0UL, MATRIX_A};
var y;
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
//c//int kk;
var kk;
if (mti == N+1) /* if init_genrand() has not been called, */
//c//init_genrand(5489); /* a default initial seed is used */
this.init_genrand(5489); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
for (;kk<N-1;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
//c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
//c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK));
mt[N-1] = unsigned32(mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]);
mti = 0;
}
y = mt[mti++];
/* Tempering */
//c//y ^= (y >> 11);
//c//y ^= (y << 7) & 0x9d2c5680;
//c//y ^= (y << 15) & 0xefc60000;
//c//y ^= (y >> 18);
y = unsigned32(y ^ (y >>> 11));
y = unsigned32(y ^ ((y << 7) & 0x9d2c5680));
y = unsigned32(y ^ ((y << 15) & 0xefc60000));
y = unsigned32(y ^ (y >>> 18));
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
//c//long genrand_int31(void)
this.genrand_int31 = function ()
{
//c//return (genrand_int32()>>1);
return (this.genrand_int32()>>>1);
}
/* generates a random number on [0,1]-real-interval */
//c//double genrand_real1(void)
this.genrand_real1 = function ()
{
//c//return genrand_int32()*(1.0/4294967295.0);
return this.genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
//c//double genrand_real2(void)
this.genrand_real2 = function ()
{
//c//return genrand_int32()*(1.0/4294967296.0);
return this.genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
//c//double genrand_real3(void)
this.genrand_real3 = function ()
{
//c//return ((genrand_int32()) + 0.5)*(1.0/4294967296.0);
return ((this.genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
//c//double genrand_res53(void)
this.genrand_res53 = function ()
{
//c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
}
// Exports: Public API
// Export the twister class
exports.MersenneTwister19937 = MersenneTwister19937;
// Export a simplified function to generate random numbers
var gen = new MersenneTwister19937;
gen.init_genrand((new Date).getTime() % 1000000000);
// Added max, min range functionality, Marak Squires Sept 11 2014
exports.rand = function(max, min) {
if (max === undefined)
{
min = 0;
max = 32768;
}
return Math.floor(gen.genrand_real2() * (max - min) + min);
}
exports.seed = function(S) {
if (typeof(S) != 'number')
{
throw new Error("seed(S) must take numeric argument; is " + typeof(S));
}
gen.init_genrand(S);
}
exports.seed_array = function(A) {
if (typeof(A) != 'object')
{
throw new Error("seed_array(A) must take array of numbers; is " + typeof(A));
}
gen.init_by_array(A);
}
},{}],167:[function(require,module,exports){
/*
* password-generator
* Copyright(c) 2011-2013 Bermi Ferrer <bermi@bermilabs.com>
* MIT Licensed
*/
(function (root) {
var localName, consonant, letter, password, vowel;
letter = /[a-zA-Z]$/;
vowel = /[aeiouAEIOU]$/;
consonant = /[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]$/;
// Defines the name of the local variable the passwordGenerator library will use
// this is specially useful if window.passwordGenerator is already being used
// by your application and you want a different name. For example:
// // Declare before including the passwordGenerator library
// var localPasswordGeneratorLibraryName = 'pass';
localName = root.localPasswordGeneratorLibraryName || "generatePassword",
password = function (length, memorable, pattern, prefix) {
var char, n;
if (length == null) {
length = 10;
}
if (memorable == null) {
memorable = true;
}
if (pattern == null) {
pattern = /\w/;
}
if (prefix == null) {
prefix = '';
}
if (prefix.length >= length) {
return prefix;
}
if (memorable) {
if (prefix.match(consonant)) {
pattern = vowel;
} else {
pattern = consonant;
}
}
n = Math.floor(Math.random() * 94) + 33;
char = String.fromCharCode(n);
if (memorable) {
char = char.toLowerCase();
}
if (!char.match(pattern)) {
return password(length, memorable, pattern, prefix);
}
return password(length, memorable, pattern, "" + prefix + char);
};
((typeof exports !== 'undefined') ? exports : root)[localName] = password;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
module.exports = password;
}
}
// Establish the root object, `window` in the browser, or `global` on the server.
}(this));
},{}],168:[function(require,module,exports){
/*
Copyright (c) 2012-2014 Jeffrey Mealo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------------------------------------------------
Based loosely on Luka Pusic's PHP Script: http://360percents.com/posts/php-random-user-agent-generator/
The license for that script is as follows:
"THE BEER-WARE LICENSE" (Revision 42):
<pusic93@gmail.com> wrote this file. As long as you retain this notice you can do whatever you want with this stuff.
If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. Luka Pusic
*/
function rnd(a, b) {
//calling rnd() with no arguments is identical to rnd(0, 100)
a = a || 0;
b = b || 100;
if (typeof b === 'number' && typeof a === 'number') {
//rnd(int min, int max) returns integer between min, max
return (function (min, max) {
if (min > max) {
throw new RangeError('expected min <= max; got min = ' + min + ', max = ' + max);
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}(a, b));
}
if (Object.prototype.toString.call(a) === "[object Array]") {
//returns a random element from array (a), even weighting
return a[Math.floor(Math.random() * a.length)];
}
if (a && typeof a === 'object') {
//returns a random key from the passed object; keys are weighted by the decimal probability in their value
return (function (obj) {
var rand = rnd(0, 100) / 100, min = 0, max = 0, key, return_val;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
max = obj[key] + min;
return_val = key;
if (rand >= min && rand <= max) {
break;
}
min = min + obj[key];
}
}
return return_val;
}(a));
}
throw new TypeError('Invalid arguments passed to rnd. (' + (b ? a + ', ' + b : a) + ')');
}
function randomLang() {
return rnd(['AB', 'AF', 'AN', 'AR', 'AS', 'AZ', 'BE', 'BG', 'BN', 'BO', 'BR', 'BS', 'CA', 'CE', 'CO', 'CS',
'CU', 'CY', 'DA', 'DE', 'EL', 'EN', 'EO', 'ES', 'ET', 'EU', 'FA', 'FI', 'FJ', 'FO', 'FR', 'FY',
'GA', 'GD', 'GL', 'GV', 'HE', 'HI', 'HR', 'HT', 'HU', 'HY', 'ID', 'IS', 'IT', 'JA', 'JV', 'KA',
'KG', 'KO', 'KU', 'KW', 'KY', 'LA', 'LB', 'LI', 'LN', 'LT', 'LV', 'MG', 'MK', 'MN', 'MO', 'MS',
'MT', 'MY', 'NB', 'NE', 'NL', 'NN', 'NO', 'OC', 'PL', 'PT', 'RM', 'RO', 'RU', 'SC', 'SE', 'SK',
'SL', 'SO', 'SQ', 'SR', 'SV', 'SW', 'TK', 'TR', 'TY', 'UK', 'UR', 'UZ', 'VI', 'VO', 'YI', 'ZH']);
}
function randomBrowserAndOS() {
var browser = rnd({
chrome: .45132810566,
iexplorer: .27477061836,
firefox: .19384170608,
safari: .06186781118,
opera: .01574236955
}),
os = {
chrome: {win: .89, mac: .09 , lin: .02},
firefox: {win: .83, mac: .16, lin: .01},
opera: {win: .91, mac: .03 , lin: .06},
safari: {win: .04 , mac: .96 },
iexplorer: ['win']
};
return [browser, rnd(os[browser])];
}
function randomProc(arch) {
var procs = {
lin:['i686', 'x86_64'],
mac: {'Intel' : .48, 'PPC': .01, 'U; Intel':.48, 'U; PPC' :.01},
win:['', 'WOW64', 'Win64; x64']
};
return rnd(procs[arch]);
}
function randomRevision(dots) {
var return_val = '';
//generate a random revision
//dots = 2 returns .x.y where x & y are between 0 and 9
for (var x = 0; x < dots; x++) {
return_val += '.' + rnd(0, 9);
}
return return_val;
}
var version_string = {
net: function () {
return [rnd(1, 4), rnd(0, 9), rnd(10000, 99999), rnd(0, 9)].join('.');
},
nt: function () {
return rnd(5, 6) + '.' + rnd(0, 3);
},
ie: function () {
return rnd(7, 11);
},
trident: function () {
return rnd(3, 7) + '.' + rnd(0, 1);
},
osx: function (delim) {
return [10, rnd(5, 10), rnd(0, 9)].join(delim || '.');
},
chrome: function () {
return [rnd(13, 39), 0, rnd(800, 899), 0].join('.');
},
presto: function () {
return '2.9.' + rnd(160, 190);
},
presto2: function () {
return rnd(10, 12) + '.00';
},
safari: function () {
return rnd(531, 538) + '.' + rnd(0, 2) + '.' + rnd(0,2);
}
};
var browser = {
firefox: function firefox(arch) {
//https://developer.mozilla.org/en-US/docs/Gecko_user_agent_string_reference
var firefox_ver = rnd(5, 15) + randomRevision(2),
gecko_ver = 'Gecko/20100101 Firefox/' + firefox_ver,
proc = randomProc(arch),
os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + ((proc) ? '; ' + proc : '')
: (arch === 'mac') ? '(Macintosh; ' + proc + ' Mac OS X ' + version_string.osx()
: '(X11; Linux ' + proc;
return 'Mozilla/5.0 ' + os_ver + '; rv:' + firefox_ver.slice(0, -2) + ') ' + gecko_ver;
},
iexplorer: function iexplorer() {
var ver = version_string.ie();
if (ver >= 11) {
//http://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx
return 'Mozilla/5.0 (Windows NT 6.' + rnd(1,3) + '; Trident/7.0; ' + rnd(['Touch; ', '']) + 'rv:11.0) like Gecko';
}
//http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx
return 'Mozilla/5.0 (compatible; MSIE ' + ver + '.0; Windows NT ' + version_string.nt() + '; Trident/' +
version_string.trident() + ((rnd(0, 1) === 1) ? '; .NET CLR ' + version_string.net() : '') + ')';
},
opera: function opera(arch) {
//http://www.opera.com/docs/history/
var presto_ver = ' Presto/' + version_string.presto() + ' Version/' + version_string.presto2() + ')',
os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + '; U; ' + randomLang() + presto_ver
: (arch === 'lin') ? '(X11; Linux ' + randomProc(arch) + '; U; ' + randomLang() + presto_ver
: '(Macintosh; Intel Mac OS X ' + version_string.osx() + ' U; ' + randomLang() + ' Presto/' +
version_string.presto() + ' Version/' + version_string.presto2() + ')';
return 'Opera/' + rnd(9, 14) + '.' + rnd(0, 99) + ' ' + os_ver;
},
safari: function safari(arch) {
var safari = version_string.safari(),
ver = rnd(4, 7) + '.' + rnd(0,1) + '.' + rnd(0,10),
os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X '+ version_string.osx('_') + ' rv:' + rnd(2, 6) + '.0; '+ randomLang() + ') '
: '(Windows; U; Windows NT ' + version_string.nt() + ')';
return 'Mozilla/5.0 ' + os_ver + 'AppleWebKit/' + safari + ' (KHTML, like Gecko) Version/' + ver + ' Safari/' + safari;
},
chrome: function chrome(arch) {
var safari = version_string.safari(),
os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X ' + version_string.osx('_') + ') '
: (arch === 'win') ? '(Windows; U; Windows NT ' + version_string.nt() + ')'
: '(X11; Linux ' + randomProc(arch);
return 'Mozilla/5.0 ' + os_ver + ' AppleWebKit/' + safari + ' (KHTML, like Gecko) Chrome/' + version_string.chrome() + ' Safari/' + safari;
}
};
exports.generate = function generate() {
var random = randomBrowserAndOS();
return browser[random[0]](random[1]);
};
},{}],169:[function(require,module,exports){
var ret = require('ret');
var DRange = require('discontinuous-range');
var types = ret.types;
/**
* If code is alphabetic, converts to other case.
* If not alphabetic, returns back code.
*
* @param {Number} code
* @return {Number}
*/
function toOtherCase(code) {
return code + (97 <= code && code <= 122 ? -32 :
65 <= code && code <= 90 ? 32 : 0);
}
/**
* Randomly returns a true or false value.
*
* @return {Boolean}
*/
function randBool() {
return !this.randInt(0, 1);
}
/**
* Randomly selects and returns a value from the array.
*
* @param {Array.<Object>} arr
* @return {Object}
*/
function randSelect(arr) {
if (arr instanceof DRange) {
return arr.index(this.randInt(0, arr.length - 1));
}
return arr[this.randInt(0, arr.length - 1)];
}
/**
* expands a token to a DiscontinuousRange of characters which has a
* length and an index function (for random selecting)
*
* @param {Object} token
* @return {DiscontinuousRange}
*/
function expand(token) {
if (token.type === ret.types.CHAR) return new DRange(token.value);
if (token.type === ret.types.RANGE) return new DRange(token.from, token.to);
if (token.type === ret.types.SET) {
var drange = new DRange();
for (var i = 0; i < token.set.length; i++) {
var subrange = expand.call(this, token.set[i]);
drange.add(subrange);
if (this.ignoreCase) {
for (var j = 0; j < subrange.length; j++) {
var code = subrange.index(j);
var otherCaseCode = toOtherCase(code);
if (code !== otherCaseCode) {
drange.add(otherCaseCode);
}
}
}
}
if (token.not) {
return this.defaultRange.clone().subtract(drange);
} else {
return drange;
}
}
throw new Error('unexpandable token type: ' + token.type);
}
/**
* @constructor
* @param {RegExp|String} regexp
* @param {String} m
*/
var RandExp = module.exports = function(regexp, m) {
this.defaultRange = this.defaultRange.clone();
if (regexp instanceof RegExp) {
this.ignoreCase = regexp.ignoreCase;
this.multiline = regexp.multiline;
if (typeof regexp.max === 'number') {
this.max = regexp.max;
}
regexp = regexp.source;
} else if (typeof regexp === 'string') {
this.ignoreCase = m && m.indexOf('i') !== -1;
this.multiline = m && m.indexOf('m') !== -1;
} else {
throw new Error('Expected a regexp or string');
}
this.tokens = ret(regexp);
};
// When a repetitional token has its max set to Infinite,
// randexp won't actually generate a random amount between min and Infinite
// instead it will see Infinite as min + 100.
RandExp.prototype.max = 100;
// Generates the random string.
RandExp.prototype.gen = function() {
return gen.call(this, this.tokens, []);
};
// Enables use of randexp with a shorter call.
RandExp.randexp = function(regexp, m) {
var randexp;
if (regexp._randexp === undefined) {
randexp = new RandExp(regexp, m);
regexp._randexp = randexp;
} else {
randexp = regexp._randexp;
if (typeof regexp.max === 'number') {
randexp.max = regexp.max;
}
if (regexp.defaultRange instanceof DRange) {
randexp.defaultRange = regexp.defaultRange;
}
if (typeof regexp.randInt === 'function') {
randexp.randInt = regexp.randInt;
}
}
return randexp.gen();
};
// This enables sugary /regexp/.gen syntax.
RandExp.sugar = function() {
/* jshint freeze:false */
RegExp.prototype.gen = function() {
return RandExp.randexp(this);
};
};
// This allows expanding to include additional characters
// for instance: RandExp.defaultRange.add(0, 65535);
RandExp.prototype.defaultRange = new DRange(32, 126);
/**
* Randomly generates and returns a number between a and b (inclusive).
*
* @param {Number} a
* @param {Number} b
* @return {Number}
*/
RandExp.prototype.randInt = function(a, b) {
return a + Math.floor(Math.random() * (1 + b - a));
};
/**
* Generate random string modeled after given tokens.
*
* @param {Object} token
* @param {Array.<String>} groups
* @return {String}
*/
function gen(token, groups) {
var stack, str, n, i, l;
switch (token.type) {
case types.ROOT:
case types.GROUP:
if (token.notFollowedBy) { return ''; }
// Insert placeholder until group string is generated.
if (token.remember && token.groupNumber === undefined) {
token.groupNumber = groups.push(null) - 1;
}
stack = token.options ?
randSelect.call(this, token.options) : token.stack;
str = '';
for (i = 0, l = stack.length; i < l; i++) {
str += gen.call(this, stack[i], groups);
}
if (token.remember) {
groups[token.groupNumber] = str;
}
return str;
case types.POSITION:
// Do nothing for now.
return '';
case types.SET:
var expanded_set = expand.call(this, token);
if (!expanded_set.length) return '';
return String.fromCharCode(randSelect.call(this, expanded_set));
case types.REPETITION:
// Randomly generate number between min and max.
n = this.randInt(token.min,
token.max === Infinity ? token.min + this.max : token.max);
str = '';
for (i = 0; i < n; i++) {
str += gen.call(this, token.value, groups);
}
return str;
case types.REFERENCE:
return groups[token.value - 1] || '';
case types.CHAR:
var code = this.ignoreCase && randBool.call(this) ?
toOtherCase(token.value) : token.value;
return String.fromCharCode(code);
}
}
},{"discontinuous-range":170,"ret":171}],170:[function(require,module,exports){
//protected helper class
function _SubRange(low, high) {
this.low = low;
this.high = high;
this.length = 1 + high - low;
}
_SubRange.prototype.overlaps = function (range) {
return !(this.high < range.low || this.low > range.high);
};
_SubRange.prototype.touches = function (range) {
return !(this.high + 1 < range.low || this.low - 1 > range.high);
};
//returns inclusive combination of _SubRanges as a _SubRange
_SubRange.prototype.add = function (range) {
return this.touches(range) && new _SubRange(Math.min(this.low, range.low), Math.max(this.high, range.high));
};
//returns subtraction of _SubRanges as an array of _SubRanges (there's a case where subtraction divides it in 2)
_SubRange.prototype.subtract = function (range) {
if (!this.overlaps(range)) return false;
if (range.low <= this.low && range.high >= this.high) return [];
if (range.low > this.low && range.high < this.high) return [new _SubRange(this.low, range.low - 1), new _SubRange(range.high + 1, this.high)];
if (range.low <= this.low) return [new _SubRange(range.high + 1, this.high)];
return [new _SubRange(this.low, range.low - 1)];
};
_SubRange.prototype.toString = function () {
if (this.low == this.high) return this.low.toString();
return this.low + '-' + this.high;
};
_SubRange.prototype.clone = function () {
return new _SubRange(this.low, this.high);
};
function DiscontinuousRange(a, b) {
if (this instanceof DiscontinuousRange) {
this.ranges = [];
this.length = 0;
if (a !== undefined) this.add(a, b);
} else {
return new DiscontinuousRange(a, b);
}
}
function _update_length(self) {
self.length = self.ranges.reduce(function (previous, range) {return previous + range.length}, 0);
}
DiscontinuousRange.prototype.add = function (a, b) {
var self = this;
function _add(subrange) {
var new_ranges = [];
var i = 0;
while (i < self.ranges.length && !subrange.touches(self.ranges[i])) {
new_ranges.push(self.ranges[i].clone());
i++;
}
while (i < self.ranges.length && subrange.touches(self.ranges[i])) {
subrange = subrange.add(self.ranges[i]);
i++;
}
new_ranges.push(subrange);
while (i < self.ranges.length) {
new_ranges.push(self.ranges[i].clone());
i++;
}
self.ranges = new_ranges;
_update_length(self);
}
if (a instanceof DiscontinuousRange) {
a.ranges.forEach(_add);
} else {
if (a instanceof _SubRange) {
_add(a);
} else {
if (b === undefined) b = a;
_add(new _SubRange(a, b));
}
}
return this;
};
DiscontinuousRange.prototype.subtract = function (a, b) {
var self = this;
function _subtract(subrange) {
var new_ranges = [];
var i = 0;
while (i < self.ranges.length && !subrange.overlaps(self.ranges[i])) {
new_ranges.push(self.ranges[i].clone());
i++;
}
while (i < self.ranges.length && subrange.overlaps(self.ranges[i])) {
new_ranges = new_ranges.concat(self.ranges[i].subtract(subrange));
i++;
}
while (i < self.ranges.length) {
new_ranges.push(self.ranges[i].clone());
i++;
}
self.ranges = new_ranges;
_update_length(self);
}
if (a instanceof DiscontinuousRange) {
a.ranges.forEach(_subtract);
} else {
if (a instanceof _SubRange) {
_subtract(a);
} else {
if (b === undefined) b = a;
_subtract(new _SubRange(a, b));
}
}
return this;
};
DiscontinuousRange.prototype.index = function (index) {
var i = 0;
while (i < this.ranges.length && this.ranges[i].length <= index) {
index -= this.ranges[i].length;
i++;
}
if (i >= this.ranges.length) return null;
return this.ranges[i].low + index;
};
DiscontinuousRange.prototype.toString = function () {
return '[ ' + this.ranges.join(', ') + ' ]'
};
DiscontinuousRange.prototype.clone = function () {
return new DiscontinuousRange(this);
};
module.exports = DiscontinuousRange;
},{}],171:[function(require,module,exports){
var util = require('./util');
var types = require('./types');
var sets = require('./sets');
var positions = require('./positions');
module.exports = function(regexpStr) {
var i = 0, l, c,
start = { type: types.ROOT, stack: []},
// Keep track of last clause/group and stack.
lastGroup = start,
last = start.stack,
groupStack = [];
var repeatErr = function(i) {
util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1));
};
// Decode a few escaped characters.
var str = util.strToChars(regexpStr);
l = str.length;
// Iterate through each character in string.
while (i < l) {
c = str[i++];
switch (c) {
// Handle escaped characters, inclues a few sets.
case '\\':
c = str[i++];
switch (c) {
case 'b':
last.push(positions.wordBoundary());
break;
case 'B':
last.push(positions.nonWordBoundary());
break;
case 'w':
last.push(sets.words());
break;
case 'W':
last.push(sets.notWords());
break;
case 'd':
last.push(sets.ints());
break;
case 'D':
last.push(sets.notInts());
break;
case 's':
last.push(sets.whitespace());
break;
case 'S':
last.push(sets.notWhitespace());
break;
default:
// Check if c is integer.
// In which case it's a reference.
if (/\d/.test(c)) {
last.push({ type: types.REFERENCE, value: parseInt(c, 10) });
// Escaped character.
} else {
last.push({ type: types.CHAR, value: c.charCodeAt(0) });
}
}
break;
// Positionals.
case '^':
last.push(positions.begin());
break;
case '$':
last.push(positions.end());
break;
// Handle custom sets.
case '[':
// Check if this class is 'anti' i.e. [^abc].
var not;
if (str[i] === '^') {
not = true;
i++;
} else {
not = false;
}
// Get all the characters in class.
var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
// Increase index by length of class.
i += classTokens[1];
last.push({
type: types.SET
, set: classTokens[0]
, not: not
});
break;
// Class of any character except \n.
case '.':
last.push(sets.anyChar());
break;
// Push group onto stack.
case '(':
// Create group.
var group = {
type: types.GROUP
, stack: []
, remember: true
};
c = str[i];
// if if this is a special kind of group.
if (c === '?') {
c = str[i + 1];
i += 2;
// Match if followed by.
if (c === '=') {
group.followedBy = true;
// Match if not followed by.
} else if (c === '!') {
group.notFollowedBy = true;
} else if (c !== ':') {
util.error(regexpStr,
'Invalid group, character \'' + c + '\' after \'?\' at column ' +
(i - 1));
}
group.remember = false;
}
// Insert subgroup into current group stack.
last.push(group);
// Remember the current group for when the group closes.
groupStack.push(lastGroup);
// Make this new group the current group.
lastGroup = group;
last = group.stack;
break;
// Pop group out of stack.
case ')':
if (groupStack.length === 0) {
util.error(regexpStr, 'Unmatched ) at column ' + (i - 1));
}
lastGroup = groupStack.pop();
// Check if this group has a PIPE.
// To get back the correct last stack.
last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
break;
// Use pipe character to give more choices.
case '|':
// Create array where options are if this is the first PIPE
// in this clause.
if (!lastGroup.options) {
lastGroup.options = [lastGroup.stack];
delete lastGroup.stack;
}
// Create a new stack and add to options for rest of clause.
var stack = [];
lastGroup.options.push(stack);
last = stack;
break;
// Repetition.
// For every repetition, remove last element from last stack
// then insert back a RANGE object.
// This design is chosen because there could be more than
// one repetition symbols in a regex i.e. `a?+{2,3}`.
case '{':
var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
if (rs !== null) {
min = parseInt(rs[1], 10);
max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
i += rs[0].length;
last.push({
type: types.REPETITION
, min: min
, max: max
, value: last.pop()
});
} else {
last.push({
type: types.CHAR
, value: 123
});
}
break;
case '?':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION
, min: 0
, max: 1
, value: last.pop()
});
break;
case '+':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION
, min: 1
, max: Infinity
, value: last.pop()
});
break;
case '*':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION
, min: 0
, max: Infinity
, value: last.pop()
});
break;
// Default is a character that is not `\[](){}?+*^$`.
default:
last.push({
type: types.CHAR
, value: c.charCodeAt(0)
});
}
}
// Check if any groups have not been closed.
if (groupStack.length !== 0) {
util.error(regexpStr, 'Unterminated group');
}
return start;
};
module.exports.types = types;
},{"./positions":172,"./sets":173,"./types":174,"./util":175}],172:[function(require,module,exports){
var types = require('./types');
exports.wordBoundary = function() {
return { type: types.POSITION, value: 'b' };
};
exports.nonWordBoundary = function() {
return { type: types.POSITION, value: 'B' };
};
exports.begin = function() {
return { type: types.POSITION, value: '^' };
};
exports.end = function() {
return { type: types.POSITION, value: '$' };
};
},{"./types":174}],173:[function(require,module,exports){
var types = require('./types');
var INTS = function() {
return [{ type: types.RANGE , from: 48, to: 57 }];
};
var WORDS = function() {
return [
{ type: types.CHAR, value: 95 }
, { type: types.RANGE, from: 97, to: 122 }
, { type: types.RANGE, from: 65, to: 90 }
].concat(INTS());
};
var WHITESPACE = function() {
return [
{ type: types.CHAR, value: 9 }
, { type: types.CHAR, value: 10 }
, { type: types.CHAR, value: 11 }
, { type: types.CHAR, value: 12 }
, { type: types.CHAR, value: 13 }
, { type: types.CHAR, value: 32 }
, { type: types.CHAR, value: 160 }
, { type: types.CHAR, value: 5760 }
, { type: types.CHAR, value: 6158 }
, { type: types.CHAR, value: 8192 }
, { type: types.CHAR, value: 8193 }
, { type: types.CHAR, value: 8194 }
, { type: types.CHAR, value: 8195 }
, { type: types.CHAR, value: 8196 }
, { type: types.CHAR, value: 8197 }
, { type: types.CHAR, value: 8198 }
, { type: types.CHAR, value: 8199 }
, { type: types.CHAR, value: 8200 }
, { type: types.CHAR, value: 8201 }
, { type: types.CHAR, value: 8202 }
, { type: types.CHAR, value: 8232 }
, { type: types.CHAR, value: 8233 }
, { type: types.CHAR, value: 8239 }
, { type: types.CHAR, value: 8287 }
, { type: types.CHAR, value: 12288 }
, { type: types.CHAR, value: 65279 }
];
};
var NOTANYCHAR = function() {
return [
{ type: types.CHAR, value: 10 }
, { type: types.CHAR, value: 13 }
, { type: types.CHAR, value: 8232 }
, { type: types.CHAR, value: 8233 }
];
};
// predefined class objects
exports.words = function() {
return { type: types.SET, set: WORDS(), not: false };
};
exports.notWords = function() {
return { type: types.SET, set: WORDS(), not: true };
};
exports.ints = function() {
return { type: types.SET, set: INTS(), not: false };
};
exports.notInts = function() {
return { type: types.SET, set: INTS(), not: true };
};
exports.whitespace = function() {
return { type: types.SET, set: WHITESPACE(), not: false };
};
exports.notWhitespace = function() {
return { type: types.SET, set: WHITESPACE(), not: true };
};
exports.anyChar = function() {
return { type: types.SET, set: NOTANYCHAR(), not: true };
};
},{"./types":174}],174:[function(require,module,exports){
module.exports = {
ROOT : 0
, GROUP : 1
, POSITION : 2
, SET : 3
, RANGE : 4
, REPETITION : 5
, REFERENCE : 6
, CHAR : 7
};
},{}],175:[function(require,module,exports){
var types = require('./types');
var sets = require('./sets');
// All of these are private and only used by randexp.
// It's assumed that they will always be called with the correct input.
var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };
/**
* Finds character representations in str and convert all to
* their respective characters
*
* @param {String} str
* @return {String}
*/
exports.strToChars = function(str) {
var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g;
str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {
if (lbs) {
return s;
}
var code = b ? 8 :
a16 ? parseInt(a16, 16) :
b16 ? parseInt(b16, 16) :
c8 ? parseInt(c8, 8) :
dctrl ? CTRL.indexOf(dctrl) :
eslsh ? SLSH[eslsh] : undefined;
var c = String.fromCharCode(code);
// Escape special regex characters.
if (/[\[\]{}\^$.|?*+()]/.test(c)) {
c = '\\' + c;
}
return c;
});
return str;
};
/**
* turns class into tokens
* reads str until it encounters a ] not preceeded by a \
*
* @param {String} str
* @param {String} regexpStr
* @return {Array.<Array.<Object>, Number>}
*/
exports.tokenizeClass = function(str, regexpStr) {
var tokens = []
, regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g
, rs, c
;
while ((rs = regexp.exec(str)) != null) {
if (rs[1]) {
tokens.push(sets.words());
} else if (rs[2]) {
tokens.push(sets.ints());
} else if (rs[3]) {
tokens.push(sets.whitespace());
} else if (rs[4]) {
tokens.push(sets.notWords());
} else if (rs[5]) {
tokens.push(sets.notInts());
} else if (rs[6]) {
tokens.push(sets.notWhitespace());
} else if (rs[7]) {
tokens.push({
type: types.RANGE
, from: (rs[8] || rs[9]).charCodeAt(0)
, to: rs[10].charCodeAt(0)
});
} else if (c = rs[12]) {
tokens.push({
type: types.CHAR
, value: c.charCodeAt(0)
});
} else {
return [tokens, regexp.lastIndex];
}
}
exports.error(regexpStr, 'Unterminated character class');
};
/**
* Shortcut to throw errors.
*
* @param {String} regexp
* @param {String} msg
*/
exports.error = function(regexp, msg) {
throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
};
},{"./sets":173,"./types":174}],"json-schema-faker":[function(require,module,exports){
module.exports = require('../lib/jsf')
.extend('faker', function() {
try {
return require('faker/locale/pl');
} catch (e) {
return null;
}
});
},{"../lib/jsf":4,"faker/locale/pl":165}]},{},["json-schema-faker"])("json-schema-faker")
}); | kennynaoh/cdnjs | ajax/libs/json-schema-faker/0.2.13/locale/pl.js | JavaScript | mit | 356,882 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Tests\Extension\Csrf\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
class FormTypeCsrfExtensionTest_ChildType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// The form needs a child in order to trigger CSRF protection by
// default
$builder->add('name', 'text');
}
public function getName()
{
return 'csrf_collection_test';
}
}
class FormTypeCsrfExtensionTest extends TypeTestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $csrfProvider;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
protected $translator;
protected function setUp()
{
$this->csrfProvider = $this->getMock('Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface');
$this->translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
parent::setUp();
}
protected function tearDown()
{
$this->csrfProvider = null;
$this->translator = null;
parent::tearDown();
}
protected function getExtensions()
{
return array_merge(parent::getExtensions(), array(
new CsrfExtension($this->csrfProvider, $this->translator),
));
}
public function testCsrfProtectionByDefaultIfRootAndCompound()
{
$view = $this->factory
->create('form', null, array(
'csrf_field_name' => 'csrf',
'compound' => true,
))
->createView();
$this->assertTrue(isset($view['csrf']));
}
public function testNoCsrfProtectionByDefaultIfCompoundButNotRoot()
{
$view = $this->factory
->createNamedBuilder('root', 'form')
->add($this->factory
->createNamedBuilder('form', 'form', null, array(
'csrf_field_name' => 'csrf',
'compound' => true,
))
)
->getForm()
->get('form')
->createView();
$this->assertFalse(isset($view['csrf']));
}
public function testNoCsrfProtectionByDefaultIfRootButNotCompound()
{
$view = $this->factory
->create('form', null, array(
'csrf_field_name' => 'csrf',
'compound' => false,
))
->createView();
$this->assertFalse(isset($view['csrf']));
}
public function testCsrfProtectionCanBeDisabled()
{
$view = $this->factory
->create('form', null, array(
'csrf_field_name' => 'csrf',
'csrf_protection' => false,
'compound' => true,
))
->createView();
$this->assertFalse(isset($view['csrf']));
}
public function testGenerateCsrfToken()
{
$this->csrfProvider->expects($this->once())
->method('generateCsrfToken')
->with('%INTENTION%')
->will($this->returnValue('token'));
$view = $this->factory
->create('form', null, array(
'csrf_field_name' => 'csrf',
'csrf_provider' => $this->csrfProvider,
'intention' => '%INTENTION%',
'compound' => true,
))
->createView();
$this->assertEquals('token', $view['csrf']->vars['value']);
}
public function provideBoolean()
{
return array(
array(true),
array(false),
);
}
/**
* @dataProvider provideBoolean
*/
public function testValidateTokenOnSubmitIfRootAndCompound($valid)
{
$this->csrfProvider->expects($this->once())
->method('isCsrfTokenValid')
->with('%INTENTION%', 'token')
->will($this->returnValue($valid));
$form = $this->factory
->createBuilder('form', null, array(
'csrf_field_name' => 'csrf',
'csrf_provider' => $this->csrfProvider,
'intention' => '%INTENTION%',
'compound' => true,
))
->add('child', 'text')
->getForm();
$form->submit(array(
'child' => 'foobar',
'csrf' => 'token',
));
// Remove token from data
$this->assertSame(array('child' => 'foobar'), $form->getData());
// Validate accordingly
$this->assertSame($valid, $form->isValid());
}
public function testFailIfRootAndCompoundAndTokenMissing()
{
$this->csrfProvider->expects($this->never())
->method('isCsrfTokenValid');
$form = $this->factory
->createBuilder('form', null, array(
'csrf_field_name' => 'csrf',
'csrf_provider' => $this->csrfProvider,
'intention' => '%INTENTION%',
'compound' => true,
))
->add('child', 'text')
->getForm();
$form->submit(array(
'child' => 'foobar',
// token is missing
));
// Remove token from data
$this->assertSame(array('child' => 'foobar'), $form->getData());
// Validate accordingly
$this->assertFalse($form->isValid());
}
public function testDontValidateTokenIfCompoundButNoRoot()
{
$this->csrfProvider->expects($this->never())
->method('isCsrfTokenValid');
$form = $this->factory
->createNamedBuilder('root', 'form')
->add($this->factory
->createNamedBuilder('form', 'form', null, array(
'csrf_field_name' => 'csrf',
'csrf_provider' => $this->csrfProvider,
'intention' => '%INTENTION%',
'compound' => true,
))
)
->getForm()
->get('form');
$form->submit(array(
'child' => 'foobar',
'csrf' => 'token',
));
}
public function testDontValidateTokenIfRootButNotCompound()
{
$this->csrfProvider->expects($this->never())
->method('isCsrfTokenValid');
$form = $this->factory
->create('form', null, array(
'csrf_field_name' => 'csrf',
'csrf_provider' => $this->csrfProvider,
'intention' => '%INTENTION%',
'compound' => false,
));
$form->submit(array(
'csrf' => 'token',
));
}
public function testNoCsrfProtectionOnPrototype()
{
$prototypeView = $this->factory
->create('collection', null, array(
'type' => new FormTypeCsrfExtensionTest_ChildType(),
'options' => array(
'csrf_field_name' => 'csrf',
),
'prototype' => true,
'allow_add' => true,
))
->createView()
->vars['prototype'];
$this->assertFalse(isset($prototypeView['csrf']));
$this->assertCount(1, $prototypeView);
}
public function testsTranslateCustomErrorMessage()
{
$this->csrfProvider->expects($this->once())
->method('isCsrfTokenValid')
->with('%INTENTION%', 'token')
->will($this->returnValue(false));
$this->translator->expects($this->once())
->method('trans')
->with('Foobar')
->will($this->returnValue('[trans]Foobar[/trans]'));
$form = $this->factory
->createBuilder('form', null, array(
'csrf_field_name' => 'csrf',
'csrf_provider' => $this->csrfProvider,
'csrf_message' => 'Foobar',
'intention' => '%INTENTION%',
'compound' => true,
))
->getForm();
$form->submit(array(
'csrf' => 'token',
));
$errors = $form->getErrors();
$this->assertGreaterThan(0, count($errors));
$this->assertEquals(new FormError('[trans]Foobar[/trans]'), $errors[0]);
}
}
| hsbhathiya/AreYouReady | vendor/symfony/symfony/src/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.php | PHP | mit | 8,684 |
/** @license MIT License (c) copyright 2011-2013 original author or authors */
/**
* wire/domReady
* A base wire/domReady module that plugins can use if they need domReady. Simply
* add 'wire/domReady' to your plugin module dependencies
* (e.g. require(['wire/domReady', ...], function(domReady, ...) { ... })) and you're
* set.
*
* wire is part of the cujo.js family of libraries (http://cujojs.com/)
*
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* Returns a function that accepts a callback to be called when the DOM is ready.
*
* You can also use your AMD loader's paths config to map wire/domReady to whatever
* domReady function you might want to use. See documentation for your AMD loader
* for specific instructions. For curl.js and requirejs, it will be something like:
*
* paths: {
* 'wire/domReady': 'path/to/my/domReady'
* }
*
* @author Brian Cavalier
* @author John Hann
*/
(function(global) {
define(['require'], function(req) {
// Try require.ready first
return (global.require && global.require.ready) || function (cb) {
// If it's not available, assume a domReady! plugin is available
req(['domReady!'], function () {
// Using domReady! as a plugin will automatically wait for domReady
// so we can just call the callback.
cb();
});
};
});
})(this);
| Rithie/todomvc | examples/cujo/bower_components/wire/domReady.js | JavaScript | mit | 1,370 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Tests\Extension\Validator\ViolationMapper;
use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormConfigBuilder;
use Symfony\Component\Form\FormError;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationInterface;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class ViolationMapperTest extends \PHPUnit_Framework_TestCase
{
const LEVEL_0 = 0;
const LEVEL_1 = 1;
const LEVEL_1B = 2;
const LEVEL_2 = 3;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $dispatcher;
/**
* @var ViolationMapper
*/
private $mapper;
/**
* @var string
*/
private $message;
/**
* @var string
*/
private $messageTemplate;
/**
* @var array
*/
private $params;
protected function setUp()
{
$this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
$this->mapper = new ViolationMapper();
$this->message = 'Message';
$this->messageTemplate = 'Message template';
$this->params = array('foo' => 'bar');
}
protected function getForm($name = 'name', $propertyPath = null, $dataClass = null, $errorMapping = array(), $inheritData = false, $synchronized = true)
{
$config = new FormConfigBuilder($name, $dataClass, $this->dispatcher, array(
'error_mapping' => $errorMapping,
));
$config->setMapped(true);
$config->setInheritData($inheritData);
$config->setPropertyPath($propertyPath);
$config->setCompound(true);
$config->setDataMapper($this->getDataMapper());
if (!$synchronized) {
$config->addViewTransformer(new CallbackTransformer(
function ($normData) { return $normData; },
function () { throw new TransformationFailedException(); }
));
}
return new Form($config);
}
/**
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getDataMapper()
{
return $this->getMock('Symfony\Component\Form\DataMapperInterface');
}
/**
* @param $propertyPath
*
* @return ConstraintViolation
*/
protected function getConstraintViolation($propertyPath)
{
return new ConstraintViolation($this->message, $this->messageTemplate, $this->params, null, $propertyPath, null);
}
/**
* @return FormError
*/
protected function getFormError(ConstraintViolationInterface $violation, FormInterface $form)
{
$error = new FormError($this->message, $this->messageTemplate, $this->params, null, $violation);
$error->setOrigin($form);
return $error;
}
public function testMapToFormInheritingParentDataIfDataDoesNotMatch()
{
$violation = $this->getConstraintViolation('children[address].data.foo');
$parent = $this->getForm('parent');
$child = $this->getForm('address', 'address', null, array(), true);
$grandChild = $this->getForm('street');
$parent->add($child);
$child->add($grandChild);
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $child)), iterator_to_array($child->getErrors()), $child->getName().' should have an error, but has none');
$this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
}
public function testFollowDotRules()
{
$violation = $this->getConstraintViolation('data.foo');
$parent = $this->getForm('parent', null, null, array(
'foo' => 'address',
));
$child = $this->getForm('address', null, null, array(
'.' => 'street',
));
$grandChild = $this->getForm('street', null, null, array(
'.' => 'name',
));
$grandGrandChild = $this->getForm('name');
$parent->add($child);
$child->add($grandChild);
$grandChild->add($grandGrandChild);
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $grandGrandChild)), iterator_to_array($grandGrandChild->getErrors()), $grandGrandChild->getName().' should have an error, but has none');
}
public function testAbortMappingIfNotSynchronized()
{
$violation = $this->getConstraintViolation('children[address].data.street');
$parent = $this->getForm('parent');
$child = $this->getForm('address', 'address', null, array(), false, false);
// even though "street" is synchronized, it should not have any errors
// due to its parent not being synchronized
$grandChild = $this->getForm('street', 'street');
$parent->add($child);
$child->add($grandChild);
// invoke the transformer and mark the form unsynchronized
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
}
public function testAbortDotRuleMappingIfNotSynchronized()
{
$violation = $this->getConstraintViolation('data.address');
$parent = $this->getForm('parent');
$child = $this->getForm('address', 'address', null, array(
'.' => 'street',
), false, false);
// even though "street" is synchronized, it should not have any errors
// due to its parent not being synchronized
$grandChild = $this->getForm('street');
$parent->add($child);
$child->add($grandChild);
// invoke the transformer and mark the form unsynchronized
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
}
public function testAbortMappingIfNotSubmitted()
{
$violation = $this->getConstraintViolation('children[address].data.street');
$parent = $this->getForm('parent');
$child = $this->getForm('address', 'address');
$grandChild = $this->getForm('street', 'street');
$parent->add($child);
$child->add($grandChild);
// Disable automatic submission of missing fields
$parent->submit(array(), false);
$child->submit(array(), false);
// $grandChild is not submitted
$this->mapper->mapViolation($violation, $parent);
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
}
public function testAbortDotRuleMappingIfNotSubmitted()
{
$violation = $this->getConstraintViolation('data.address');
$parent = $this->getForm('parent');
$child = $this->getForm('address', 'address', null, array(
'.' => 'street',
));
$grandChild = $this->getForm('street');
$parent->add($child);
$child->add($grandChild);
// Disable automatic submission of missing fields
$parent->submit(array(), false);
$child->submit(array(), false);
// $grandChild is not submitted
$this->mapper->mapViolation($violation, $parent);
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
}
public function provideDefaultTests()
{
// The mapping must be deterministic! If a child has the property path "[street]",
// "data[street]" should be mapped, but "data.street" should not!
return array(
// mapping target, child name, its property path, grand child name, its property path, violation path
array(self::LEVEL_0, 'address', 'address', 'street', 'street', ''),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.address.street'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.address.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'data.address[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'data.address[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address].data'),
array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].data[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'data.address.street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'data.address.street.prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'data.address[street]'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'data.address[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address].street'),
array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address].street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address][street]'),
array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address].data'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address.street'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address.street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address[street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address[street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'data[address].street'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'data[address].street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'data[address][street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'data[address][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address].data'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address.street'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address.street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address[street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'data[address].street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'data[address].street.prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'data[address][street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'data[address][street].prop'),
array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'children[address].data'),
array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'data.person.address.street'),
array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'data.person.address.street.prop'),
array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'data.person.address[street]'),
array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'data.person.address[street].prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address].street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address].street.prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address][street]'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address][street].prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address.street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address.street.prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address[street]'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address[street].prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address].street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address].street.prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address][street]'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'children[address].data'),
array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].data[street].prop'),
array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'data.person.address.street'),
array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'data.person.address.street.prop'),
array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'data.person.address[street]'),
array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'data.person.address[street].prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address].street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address].street.prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address][street]'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address][street].prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address.street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address.street.prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address[street]'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address[street].prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address].street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address].street.prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address][street]'),
array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'children[address].data'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address.street'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address.street.prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address[street]'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address[street].prop'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'data.person[address].street'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'data.person[address].street.prop'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'data.person[address][street]'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'data.person[address][street].prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address.street'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address.street.prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address[street]'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address[street].prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address].street'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address].street.prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address][street]'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'children[address].data'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address.street'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address.street.prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address[street]'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address[street].prop'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'data.person[address].street'),
array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'data.person[address].street.prop'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'data.person[address][street]'),
array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'data.person[address][street].prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address.street'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address.street.prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address[street]'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address[street].prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address].street'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address].street.prop'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address][street]'),
array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'children[address].data'),
array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address.street'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address.street.prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address[street]'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address[street].prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address].street'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address].street.prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address][street]'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address][street].prop'),
array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'data[person].address.street'),
array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'data[person].address.street.prop'),
array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'data[person].address[street]'),
array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'data[person].address[street].prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address].street'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address].street.prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address][street]'),
array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'children[address].data'),
array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address.street'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address.street.prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address[street]'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address[street].prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address].street'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address].street.prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address][street]'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address][street].prop'),
array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'data[person].address.street'),
array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'data[person].address.street.prop'),
array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'data[person].address[street]'),
array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'data[person].address[street].prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address].street'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address].street.prop'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address][street]'),
array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address]'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address].data'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address.street'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address.street.prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address[street]'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address[street].prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address].street'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address].street.prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address][street]'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address][street].prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address.street'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address.street.prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address[street]'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address[street].prop'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'data[person][address].street'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'data[person][address].street.prop'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'data[person][address][street]'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'children[address].data'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].data[street].prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address.street'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address.street.prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address[street]'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address[street].prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address].street'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address].street.prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address][street]'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address][street].prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address.street'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address.street.prop'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address[street]'),
array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address[street].prop'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'data[person][address].street'),
array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'data[person][address].street.prop'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'data[person][address][street]'),
array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'data[person][address][street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.office'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].data.office.street'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].data.office.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.office[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office].street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office].street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office][street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office][street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'data.address.office.street'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'data.address.office.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address.office[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address.office[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office].street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office].street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office][street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office][street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office.street'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office.street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office[street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office].street'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office].street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office][street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data.office'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].data.office.street'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].data.office.street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data.office[street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office].street'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office].street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office][street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office][street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office.street'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office.street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office[street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office[street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office].street'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office].street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office][street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'data[address].office.street'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'data[address].office.street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address].office[street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address].office[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office].street'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office].street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office][street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office][street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data.office'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data.office.street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data.office.street.prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].data.office[street]'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office].street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office].street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office][street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office][street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address.office.street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address.office.street.prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'data.address.office[street]'),
array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'data.address.office[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office].street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office].street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office][street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office][street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office.street'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office.street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office[street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office].street'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office].street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office][street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office.street'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office.street.prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office[street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office].street'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office].street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office][street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office][street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office.street'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office.street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office[street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office[street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office].street'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office].street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office][street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office][street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address].office.street'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address].office.street.prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'data[address].office[street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'data[address].office[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office].street'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office].street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office][street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office][street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office.street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data[office]'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].data[office].street'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].data[office].street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data[office][street]'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data[office][street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office.street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office[street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'data.address[office].street'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'data.address[office].street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address[office][street]'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address[office][street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office.street'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office.street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office[street]'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office].street'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office].street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office][street]'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office.street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office.street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office[street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data[office]'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].data[office].street'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].data[office].street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data[office][street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data[office][street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office.street'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office.street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office[street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office[street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office].street'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office].street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office][street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office][street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office.street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office.street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office[street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office[street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'data[address][office].street'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'data[address][office].street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address][office][street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address][office][street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office.street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data[office]'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data[office].street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data[office].street.prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].data[office][street]'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].data[office][street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office.street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office[street].prop'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address[office].street'),
array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address[office].street.prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'data.address[office][street]'),
array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'data.address[office][street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office.street'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office.street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office[street]'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office].street'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office].street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office][street]'),
array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office.street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office.street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office[street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office]'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office].street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office].street.prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office][street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office][street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office.street'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office.street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office[street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office[street].prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office].street'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office].street.prop'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office][street]'),
array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office][street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office.street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office.street.prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office[street]'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office[street].prop'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address][office].street'),
array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address][office].street.prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'data[address][office][street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'data[address][office][street].prop'),
// Edge cases which must not occur
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address][street]'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address][street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address][street]'),
array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address][street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address][street].prop'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address][street]'),
array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address][street].prop'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'children[person].children[address].children[street]'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'children[person].children[address].data.street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'children[person].data.address.street'),
array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.address.street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].children[office].children[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].children[office].data.street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.street'),
array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address.street'),
);
}
/**
* @dataProvider provideDefaultTests
*/
public function testDefaultErrorMapping($target, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
{
$violation = $this->getConstraintViolation($violationPath);
$parent = $this->getForm('parent');
$child = $this->getForm($childName, $childPath);
$grandChild = $this->getForm($grandChildName, $grandChildPath);
$parent->add($child);
$child->add($grandChild);
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
if (self::LEVEL_0 === $target) {
$this->assertEquals(array($this->getFormError($violation, $parent)), iterator_to_array($parent->getErrors()), $parent->getName().' should have an error, but has none');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} elseif (self::LEVEL_1 === $target) {
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $child)), iterator_to_array($child->getErrors()), $childName.' should have an error, but has none');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} else {
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $grandChild)), iterator_to_array($grandChild->getErrors()), $grandChildName.' should have an error, but has none');
}
}
public function provideCustomDataErrorTests()
{
return array(
// mapping target, error mapping, child name, its property path, grand child name, its property path, violation path
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo]'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo].prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address]'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address].prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo]'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address.prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address]'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address].prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo.street'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo[street]'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo[street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo].street'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo].street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo][street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo][street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address.street'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address[street]'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address[street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address].street'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address].street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address][street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address][street].prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street]'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street].prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address.street'),
array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address.street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address[street]'),
array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address[street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address].street'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address].street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address][street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address][street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street]'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address.street'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address.street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address[street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address[street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address].street'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address].street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address][street]'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address][street].prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street]'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street].prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street]'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street].prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street].prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address.street'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address.street.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address[street]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address[street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address].street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address].street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address][street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address][street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street].prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street.prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street]'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street].prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address.street'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address.street.prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address[street]'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address[street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address].street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address].street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address][street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address][street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street].prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address.street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address.street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address[street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address[street].prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address].street'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address].street.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address][street]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address][street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street].prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street.prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street]'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street].prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street'),
array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street.prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street]'),
array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street].prop'),
array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),
array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),
array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),
array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', 'street', 'data.foo'),
array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', 'street', 'data.foo.prop'),
array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo]'),
array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo].prop'),
array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo'),
array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo.prop'),
array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo]'),
array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo].prop'),
array(self::LEVEL_2, 'foo', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo'),
array(self::LEVEL_2, 'foo', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo.prop'),
array(self::LEVEL_2, '[foo]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo]'),
array(self::LEVEL_2, '[foo]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo].prop'),
array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', 'street', 'data.foo.bar'),
array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', 'street', 'data[foo].bar'),
array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),
array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo.bar'),
array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo.bar.prop'),
array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo[bar]'),
array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo[bar].prop'),
array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo].bar'),
array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo].bar.prop'),
array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo][bar]'),
array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo][bar].prop'),
array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo.bar'),
array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo.bar.prop'),
array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo[bar]'),
array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo[bar].prop'),
array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo].bar'),
array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo].bar.prop'),
array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo][bar]'),
array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo][bar].prop'),
// Edge cases
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street'),
array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street]'),
array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street].prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street.prop'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street]'),
array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street].prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street.prop'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street]'),
array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street].prop'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street'),
array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street]'),
array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street].prop'),
);
}
/**
* @dataProvider provideCustomDataErrorTests
*/
public function testCustomDataErrorMapping($target, $mapFrom, $mapTo, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
{
$violation = $this->getConstraintViolation($violationPath);
$parent = $this->getForm('parent', null, null, array($mapFrom => $mapTo));
$child = $this->getForm($childName, $childPath);
$grandChild = $this->getForm($grandChildName, $grandChildPath);
$parent->add($child);
$child->add($grandChild);
// Add a field mapped to the first element of $mapFrom
// to try to distract the algorithm
// Only add it if we expect the error to come up on a different
// level than LEVEL_0, because in this case the error would
// (correctly) be mapped to the distraction field
if ($target !== self::LEVEL_0) {
$mapFromPath = new PropertyPath($mapFrom);
$mapFromPrefix = $mapFromPath->isIndex(0)
? '['.$mapFromPath->getElement(0).']'
: $mapFromPath->getElement(0);
$distraction = $this->getForm('distraction', $mapFromPrefix);
$parent->add($distraction);
}
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
if ($target !== self::LEVEL_0) {
$this->assertCount(0, $distraction->getErrors(), 'distraction should not have an error, but has one');
}
if (self::LEVEL_0 === $target) {
$this->assertEquals(array($this->getFormError($violation, $parent)), iterator_to_array($parent->getErrors()), $parent->getName().' should have an error, but has none');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} elseif (self::LEVEL_1 === $target) {
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $child)), iterator_to_array($child->getErrors()), $childName.' should have an error, but has none');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} else {
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $grandChild)), iterator_to_array($grandChild->getErrors()), $grandChildName.' should have an error, but has none');
}
}
public function provideCustomFormErrorTests()
{
// This case is different than the data errors, because here the
// left side of the mapping refers to the property path of the actual
// children. In other words, a child error only works if
// 1) the error actually maps to an existing child and
// 2) the property path of that child (relative to the form providing
// the mapping) matches the left side of the mapping
return array(
// mapping target, map from, map to, child name, its property path, grand child name, its property path, violation path
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street].prop'),
// Property path of the erroneous field and mapping must match exactly
array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),
array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),
array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
array(self::LEVEL_2, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
array(self::LEVEL_2, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].children[street].data'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].children[street].data.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data.street'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data.street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data[street]'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data[street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street].prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].children[street].data'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].children[street].data.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data.street'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data[street]'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data[street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].children[street].data'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].children[street].data.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data.street'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data.street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data[street]'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data[street].prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street].data'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street].data.prop'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street.prop'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street].prop'),
// Map to a nested child
array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo]'),
array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo]'),
array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo]'),
array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo]'),
// Map from a nested child
array(self::LEVEL_1B, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_1B, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1B, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1B, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1B, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1B, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_1B, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_1B, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1B, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_1B, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1B, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
array(self::LEVEL_1, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
array(self::LEVEL_1B, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
);
}
/**
* @dataProvider provideCustomFormErrorTests
*/
public function testCustomFormErrorMapping($target, $mapFrom, $mapTo, $errorName, $errorPath, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
{
$violation = $this->getConstraintViolation($violationPath);
$parent = $this->getForm('parent', null, null, array($mapFrom => $mapTo));
$child = $this->getForm($childName, $childPath);
$grandChild = $this->getForm($grandChildName, $grandChildPath);
$errorChild = $this->getForm($errorName, $errorPath);
$parent->add($child);
$parent->add($errorChild);
$child->add($grandChild);
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
if (self::LEVEL_0 === $target) {
$this->assertCount(0, $errorChild->getErrors(), $errorName.' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $parent)), iterator_to_array($parent->getErrors()), $parent->getName().' should have an error, but has none');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} elseif (self::LEVEL_1 === $target) {
$this->assertCount(0, $errorChild->getErrors(), $errorName.' should not have an error, but has one');
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $child)), iterator_to_array($child->getErrors()), $childName.' should have an error, but has none');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} elseif (self::LEVEL_1B === $target) {
$this->assertEquals(array($this->getFormError($violation, $errorChild)), iterator_to_array($errorChild->getErrors()), $errorName.' should have an error, but has none');
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} else {
$this->assertCount(0, $errorChild->getErrors(), $errorName.' should not have an error, but has one');
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $grandChild)), iterator_to_array($grandChild->getErrors()), $grandChildName.' should have an error, but has none');
}
}
public function provideErrorTestsForFormInheritingParentData()
{
return array(
// mapping target, child name, its property path, grand child name, its property path, violation path
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data.prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street.prop'),
array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street]'),
array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street].prop'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.street'),
array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address.street'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address.street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address[street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address[street].prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street.prop'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street]'),
array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street].prop'),
);
}
/**
* @dataProvider provideErrorTestsForFormInheritingParentData
*/
public function testErrorMappingForFormInheritingParentData($target, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
{
$violation = $this->getConstraintViolation($violationPath);
$parent = $this->getForm('parent');
$child = $this->getForm($childName, $childPath, null, array(), true);
$grandChild = $this->getForm($grandChildName, $grandChildPath);
$parent->add($child);
$child->add($grandChild);
$parent->submit(array());
$this->mapper->mapViolation($violation, $parent);
if (self::LEVEL_0 === $target) {
$this->assertEquals(array($this->getFormError($violation, $parent)), iterator_to_array($parent->getErrors()), $parent->getName().' should have an error, but has none');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} elseif (self::LEVEL_1 === $target) {
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $child)), iterator_to_array($child->getErrors()), $childName.' should have an error, but has none');
$this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
} else {
$this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
$this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
$this->assertEquals(array($this->getFormError($violation, $grandChild)), iterator_to_array($grandChild->getErrors()), $grandChildName.' should have an error, but has none');
}
}
}
| Kvebalas/weather | vendor/symfony/symfony/src/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.php | PHP | mit | 145,479 |
/*! emojione 15-04-2015 */
!function(a){a.emojioneList={":hash:":["0023-fe0f-20e3","0023-20e3"],":zero:":["0030-fe0f-20e3","0030-20e3"],":one:":["0031-fe0f-20e3","0031-20e3"],":two:":["0032-fe0f-20e3","0032-20e3"],":three:":["0033-fe0f-20e3","0033-20e3"],":four:":["0034-fe0f-20e3","0034-20e3"],":five:":["0035-fe0f-20e3","0035-20e3"],":six:":["0036-fe0f-20e3","0036-20e3"],":seven:":["0037-fe0f-20e3","0037-20e3"],":eight:":["0038-fe0f-20e3","0038-20e3"],":nine:":["0039-fe0f-20e3","0039-20e3"],":copyright:":["00a9"],":registered:":["00ae"],":bangbang:":["203c-fe0f","203c"],":interrobang:":["2049-fe0f","2049"],":tm:":["2122"],":information_source:":["2139-fe0f","2139"],":left_right_arrow:":["2194-fe0f","2194"],":arrow_up_down:":["2195-fe0f","2195"],":arrow_upper_left:":["2196-fe0f","2196"],":arrow_upper_right:":["2197-fe0f","2197"],":arrow_lower_right:":["2198-fe0f","2198"],":arrow_lower_left:":["2199-fe0f","2199"],":leftwards_arrow_with_hook:":["21a9-fe0f","21a9"],":arrow_right_hook:":["21aa-fe0f","21aa"],":watch:":["231a-fe0f","231a"],":hourglass:":["231b-fe0f","231b"],":fast_forward:":["23e9"],":rewind:":["23ea"],":arrow_double_up:":["23eb"],":arrow_double_down:":["23ec"],":alarm_clock:":["23f0"],":hourglass_flowing_sand:":["23f3"],":m:":["24c2-fe0f","24c2"],":black_small_square:":["25aa-fe0f","25aa"],":white_small_square:":["25ab-fe0f","25ab"],":arrow_forward:":["25b6-fe0f","25b6"],":arrow_backward:":["25c0-fe0f","25c0"],":white_medium_square:":["25fb-fe0f","25fb"],":black_medium_square:":["25fc-fe0f","25fc"],":white_medium_small_square:":["25fd-fe0f","25fd"],":black_medium_small_square:":["25fe-fe0f","25fe"],":sunny:":["2600-fe0f","2600"],":cloud:":["2601-fe0f","2601"],":telephone:":["260e-fe0f","260e"],":ballot_box_with_check:":["2611-fe0f","2611"],":umbrella:":["2614-fe0f","2614"],":coffee:":["2615-fe0f","2615"],":point_up:":["261d-fe0f","261d"],":relaxed:":["263a-fe0f","263a"],":aries:":["2648-fe0f","2648"],":taurus:":["2649-fe0f","2649"],":gemini:":["264a-fe0f","264a"],":cancer:":["264b-fe0f","264b"],":leo:":["264c-fe0f","264c"],":virgo:":["264d-fe0f","264d"],":libra:":["264e-fe0f","264e"],":scorpius:":["264f-fe0f","264f"],":sagittarius:":["2650-fe0f","2650"],":capricorn:":["2651-fe0f","2651"],":aquarius:":["2652-fe0f","2652"],":pisces:":["2653-fe0f","2653"],":spades:":["2660-fe0f","2660"],":clubs:":["2663-fe0f","2663"],":hearts:":["2665-fe0f","2665"],":diamonds:":["2666-fe0f","2666"],":hotsprings:":["2668-fe0f","2668"],":recycle:":["267b-fe0f","267b"],":wheelchair:":["267f-fe0f","267f"],":anchor:":["2693-fe0f","2693"],":warning:":["26a0-fe0f","26a0"],":zap:":["26a1-fe0f","26a1"],":white_circle:":["26aa-fe0f","26aa"],":black_circle:":["26ab-fe0f","26ab"],":soccer:":["26bd-fe0f","26bd"],":baseball:":["26be-fe0f","26be"],":snowman:":["26c4-fe0f","26c4"],":partly_sunny:":["26c5-fe0f","26c5"],":ophiuchus:":["26ce"],":no_entry:":["26d4-fe0f","26d4"],":church:":["26ea-fe0f","26ea"],":fountain:":["26f2-fe0f","26f2"],":golf:":["26f3-fe0f","26f3"],":sailboat:":["26f5-fe0f","26f5"],":tent:":["26fa-fe0f","26fa"],":fuelpump:":["26fd-fe0f","26fd"],":scissors:":["2702-fe0f","2702"],":white_check_mark:":["2705"],":airplane:":["2708-fe0f","2708"],":envelope:":["2709-fe0f","2709"],":fist:":["270a"],":raised_hand:":["270b"],":v:":["270c-fe0f","270c"],":pencil2:":["270f-fe0f","270f"],":black_nib:":["2712-fe0f","2712"],":heavy_check_mark:":["2714-fe0f","2714"],":heavy_multiplication_x:":["2716-fe0f","2716"],":sparkles:":["2728"],":eight_spoked_asterisk:":["2733-fe0f","2733"],":eight_pointed_black_star:":["2734-fe0f","2734"],":snowflake:":["2744-fe0f","2744"],":sparkle:":["2747-fe0f","2747"],":x:":["274c"],":negative_squared_cross_mark:":["274e"],":question:":["2753"],":grey_question:":["2754"],":grey_exclamation:":["2755"],":exclamation:":["2757-fe0f","2757"],":heart:":["2764-fe0f","2764"],":heavy_plus_sign:":["2795"],":heavy_minus_sign:":["2796"],":heavy_division_sign:":["2797"],":arrow_right:":["27a1-fe0f","27a1"],":curly_loop:":["27b0"],":arrow_heading_up:":["2934-fe0f","2934"],":arrow_heading_down:":["2935-fe0f","2935"],":arrow_left:":["2b05-fe0f","2b05"],":arrow_up:":["2b06-fe0f","2b06"],":arrow_down:":["2b07-fe0f","2b07"],":black_large_square:":["2b1b-fe0f","2b1b"],":white_large_square:":["2b1c-fe0f","2b1c"],":star:":["2b50-fe0f","2b50"],":o:":["2b55-fe0f","2b55"],":wavy_dash:":["3030"],":part_alternation_mark:":["303d-fe0f","303d"],":congratulations:":["3297-fe0f","3297"],":secret:":["3299-fe0f","3299"],":mahjong:":["1f004-fe0f","1f004"],":black_joker:":["1f0cf"],":a:":["1f170"],":b:":["1f171"],":o2:":["1f17e"],":parking:":["1f17f-fe0f","1f17f"],":ab:":["1f18e"],":cl:":["1f191"],":cool:":["1f192"],":free:":["1f193"],":id:":["1f194"],":new:":["1f195"],":ng:":["1f196"],":ok:":["1f197"],":sos:":["1f198"],":up:":["1f199"],":vs:":["1f19a"],":cn:":["1f1e8-1f1f3"],":de:":["1f1e9-1f1ea"],":es:":["1f1ea-1f1f8"],":fr:":["1f1eb-1f1f7"],":gb:":["1f1ec-1f1e7"],":it:":["1f1ee-1f1f9"],":jp:":["1f1ef-1f1f5"],":kr:":["1f1f0-1f1f7"],":us:":["1f1fa-1f1f8"],":ru:":["1f1f7-1f1fa"],":koko:":["1f201"],":sa:":["1f202"],":u7121:":["1f21a-fe0f","1f21a"],":u6307:":["1f22f-fe0f","1f22f"],":u7981:":["1f232"],":u7a7a:":["1f233"],":u5408:":["1f234"],":u6e80:":["1f235"],":u6709:":["1f236"],":u6708:":["1f237"],":u7533:":["1f238"],":u5272:":["1f239"],":u55b6:":["1f23a"],":ideograph_advantage:":["1f250"],":accept:":["1f251"],":cyclone:":["1f300"],":foggy:":["1f301"],":closed_umbrella:":["1f302"],":night_with_stars:":["1f303"],":sunrise_over_mountains:":["1f304"],":sunrise:":["1f305"],":city_dusk:":["1f306"],":city_sunset:":["1f307"],":city_sunrise:":["1f307"],":rainbow:":["1f308"],":bridge_at_night:":["1f309"],":ocean:":["1f30a"],":volcano:":["1f30b"],":milky_way:":["1f30c"],":earth_asia:":["1f30f"],":new_moon:":["1f311"],":first_quarter_moon:":["1f313"],":waxing_gibbous_moon:":["1f314"],":full_moon:":["1f315"],":crescent_moon:":["1f319"],":first_quarter_moon_with_face:":["1f31b"],":star2:":["1f31f"],":stars:":["1f320"],":chestnut:":["1f330"],":seedling:":["1f331"],":palm_tree:":["1f334"],":cactus:":["1f335"],":tulip:":["1f337"],":cherry_blossom:":["1f338"],":rose:":["1f339"],":hibiscus:":["1f33a"],":sunflower:":["1f33b"],":blossom:":["1f33c"],":corn:":["1f33d"],":ear_of_rice:":["1f33e"],":herb:":["1f33f"],":four_leaf_clover:":["1f340"],":maple_leaf:":["1f341"],":fallen_leaf:":["1f342"],":leaves:":["1f343"],":mushroom:":["1f344"],":tomato:":["1f345"],":eggplant:":["1f346"],":grapes:":["1f347"],":melon:":["1f348"],":watermelon:":["1f349"],":tangerine:":["1f34a"],":banana:":["1f34c"],":pineapple:":["1f34d"],":apple:":["1f34e"],":green_apple:":["1f34f"],":peach:":["1f351"],":cherries:":["1f352"],":strawberry:":["1f353"],":hamburger:":["1f354"],":pizza:":["1f355"],":meat_on_bone:":["1f356"],":poultry_leg:":["1f357"],":rice_cracker:":["1f358"],":rice_ball:":["1f359"],":rice:":["1f35a"],":curry:":["1f35b"],":ramen:":["1f35c"],":spaghetti:":["1f35d"],":bread:":["1f35e"],":fries:":["1f35f"],":sweet_potato:":["1f360"],":dango:":["1f361"],":oden:":["1f362"],":sushi:":["1f363"],":fried_shrimp:":["1f364"],":fish_cake:":["1f365"],":icecream:":["1f366"],":shaved_ice:":["1f367"],":ice_cream:":["1f368"],":doughnut:":["1f369"],":cookie:":["1f36a"],":chocolate_bar:":["1f36b"],":candy:":["1f36c"],":lollipop:":["1f36d"],":custard:":["1f36e"],":honey_pot:":["1f36f"],":cake:":["1f370"],":bento:":["1f371"],":stew:":["1f372"],":egg:":["1f373"],":fork_and_knife:":["1f374"],":tea:":["1f375"],":sake:":["1f376"],":wine_glass:":["1f377"],":cocktail:":["1f378"],":tropical_drink:":["1f379"],":beer:":["1f37a"],":beers:":["1f37b"],":ribbon:":["1f380"],":gift:":["1f381"],":birthday:":["1f382"],":jack_o_lantern:":["1f383"],":christmas_tree:":["1f384"],":santa:":["1f385"],":fireworks:":["1f386"],":sparkler:":["1f387"],":balloon:":["1f388"],":tada:":["1f389"],":confetti_ball:":["1f38a"],":tanabata_tree:":["1f38b"],":crossed_flags:":["1f38c"],":bamboo:":["1f38d"],":dolls:":["1f38e"],":flags:":["1f38f"],":wind_chime:":["1f390"],":rice_scene:":["1f391"],":school_satchel:":["1f392"],":mortar_board:":["1f393"],":carousel_horse:":["1f3a0"],":ferris_wheel:":["1f3a1"],":roller_coaster:":["1f3a2"],":fishing_pole_and_fish:":["1f3a3"],":microphone:":["1f3a4"],":movie_camera:":["1f3a5"],":cinema:":["1f3a6"],":headphones:":["1f3a7"],":art:":["1f3a8"],":tophat:":["1f3a9"],":circus_tent:":["1f3aa"],":ticket:":["1f3ab"],":clapper:":["1f3ac"],":performing_arts:":["1f3ad"],":video_game:":["1f3ae"],":dart:":["1f3af"],":slot_machine:":["1f3b0"],":8ball:":["1f3b1"],":game_die:":["1f3b2"],":bowling:":["1f3b3"],":flower_playing_cards:":["1f3b4"],":musical_note:":["1f3b5"],":notes:":["1f3b6"],":saxophone:":["1f3b7"],":guitar:":["1f3b8"],":musical_keyboard:":["1f3b9"],":trumpet:":["1f3ba"],":violin:":["1f3bb"],":musical_score:":["1f3bc"],":running_shirt_with_sash:":["1f3bd"],":tennis:":["1f3be"],":ski:":["1f3bf"],":basketball:":["1f3c0"],":checkered_flag:":["1f3c1"],":snowboarder:":["1f3c2"],":runner:":["1f3c3"],":surfer:":["1f3c4"],":trophy:":["1f3c6"],":football:":["1f3c8"],":swimmer:":["1f3ca"],":house:":["1f3e0"],":house_with_garden:":["1f3e1"],":office:":["1f3e2"],":post_office:":["1f3e3"],":hospital:":["1f3e5"],":bank:":["1f3e6"],":atm:":["1f3e7"],":hotel:":["1f3e8"],":love_hotel:":["1f3e9"],":convenience_store:":["1f3ea"],":school:":["1f3eb"],":department_store:":["1f3ec"],":factory:":["1f3ed"],":izakaya_lantern:":["1f3ee"],":japanese_castle:":["1f3ef"],":european_castle:":["1f3f0"],":snail:":["1f40c"],":snake:":["1f40d"],":racehorse:":["1f40e"],":sheep:":["1f411"],":monkey:":["1f412"],":chicken:":["1f414"],":boar:":["1f417"],":elephant:":["1f418"],":octopus:":["1f419"],":shell:":["1f41a"],":bug:":["1f41b"],":ant:":["1f41c"],":bee:":["1f41d"],":beetle:":["1f41e"],":fish:":["1f41f"],":tropical_fish:":["1f420"],":blowfish:":["1f421"],":turtle:":["1f422"],":hatching_chick:":["1f423"],":baby_chick:":["1f424"],":hatched_chick:":["1f425"],":bird:":["1f426"],":penguin:":["1f427"],":koala:":["1f428"],":poodle:":["1f429"],":camel:":["1f42b"],":dolphin:":["1f42c"],":mouse:":["1f42d"],":cow:":["1f42e"],":tiger:":["1f42f"],":rabbit:":["1f430"],":cat:":["1f431"],":dragon_face:":["1f432"],":whale:":["1f433"],":horse:":["1f434"],":monkey_face:":["1f435"],":dog:":["1f436"],":pig:":["1f437"],":frog:":["1f438"],":hamster:":["1f439"],":wolf:":["1f43a"],":bear:":["1f43b"],":panda_face:":["1f43c"],":pig_nose:":["1f43d"],":feet:":["1f43e"],":eyes:":["1f440"],":ear:":["1f442"],":nose:":["1f443"],":lips:":["1f444"],":tongue:":["1f445"],":point_up_2:":["1f446"],":point_down:":["1f447"],":point_left:":["1f448"],":point_right:":["1f449"],":punch:":["1f44a"],":wave:":["1f44b"],":ok_hand:":["1f44c"],":thumbsup:":["1f44d"],":+1:":["1f44d"],":thumbsdown:":["1f44e"],":-1:":["1f44e"],":clap:":["1f44f"],":open_hands:":["1f450"],":crown:":["1f451"],":womans_hat:":["1f452"],":eyeglasses:":["1f453"],":necktie:":["1f454"],":shirt:":["1f455"],":jeans:":["1f456"],":dress:":["1f457"],":kimono:":["1f458"],":bikini:":["1f459"],":womans_clothes:":["1f45a"],":purse:":["1f45b"],":handbag:":["1f45c"],":pouch:":["1f45d"],":mans_shoe:":["1f45e"],":athletic_shoe:":["1f45f"],":high_heel:":["1f460"],":sandal:":["1f461"],":boot:":["1f462"],":footprints:":["1f463"],":bust_in_silhouette:":["1f464"],":boy:":["1f466"],":girl:":["1f467"],":man:":["1f468"],":woman:":["1f469"],":family:":["1f46a"],":couple:":["1f46b"],":cop:":["1f46e"],":dancers:":["1f46f"],":bride_with_veil:":["1f470"],":person_with_blond_hair:":["1f471"],":man_with_gua_pi_mao:":["1f472"],":man_with_turban:":["1f473"],":older_man:":["1f474"],":older_woman:":["1f475"],":grandma:":["1f475"],":baby:":["1f476"],":construction_worker:":["1f477"],":princess:":["1f478"],":japanese_ogre:":["1f479"],":japanese_goblin:":["1f47a"],":ghost:":["1f47b"],":angel:":["1f47c"],":alien:":["1f47d"],":space_invader:":["1f47e"],":imp:":["1f47f"],":skull:":["1f480"],":skeleton:":["1f480"],":card_index:":["1f4c7"],":information_desk_person:":["1f481"],":guardsman:":["1f482"],":dancer:":["1f483"],":lipstick:":["1f484"],":nail_care:":["1f485"],":ledger:":["1f4d2"],":massage:":["1f486"],":notebook:":["1f4d3"],":haircut:":["1f487"],":notebook_with_decorative_cover:":["1f4d4"],":barber:":["1f488"],":closed_book:":["1f4d5"],":syringe:":["1f489"],":book:":["1f4d6"],":pill:":["1f48a"],":green_book:":["1f4d7"],":kiss:":["1f48b"],":blue_book:":["1f4d8"],":love_letter:":["1f48c"],":orange_book:":["1f4d9"],":ring:":["1f48d"],":books:":["1f4da"],":gem:":["1f48e"],":name_badge:":["1f4db"],":couplekiss:":["1f48f"],":scroll:":["1f4dc"],":bouquet:":["1f490"],":pencil:":["1f4dd"],":couple_with_heart:":["1f491"],":telephone_receiver:":["1f4de"],":wedding:":["1f492"],":pager:":["1f4df"],":fax:":["1f4e0"],":heartbeat:":["1f493"],":satellite:":["1f4e1"],":loudspeaker:":["1f4e2"],":broken_heart:":["1f494"],":mega:":["1f4e3"],":outbox_tray:":["1f4e4"],":two_hearts:":["1f495"],":inbox_tray:":["1f4e5"],":package:":["1f4e6"],":sparkling_heart:":["1f496"],":e-mail:":["1f4e7"],":email:":["1f4e7"],":incoming_envelope:":["1f4e8"],":heartpulse:":["1f497"],":envelope_with_arrow:":["1f4e9"],":mailbox_closed:":["1f4ea"],":cupid:":["1f498"],":mailbox:":["1f4eb"],":postbox:":["1f4ee"],":blue_heart:":["1f499"],":newspaper:":["1f4f0"],":iphone:":["1f4f1"],":green_heart:":["1f49a"],":calling:":["1f4f2"],":vibration_mode:":["1f4f3"],":yellow_heart:":["1f49b"],":mobile_phone_off:":["1f4f4"],":signal_strength:":["1f4f6"],":purple_heart:":["1f49c"],":camera:":["1f4f7"],":video_camera:":["1f4f9"],":gift_heart:":["1f49d"],":tv:":["1f4fa"],":radio:":["1f4fb"],":revolving_hearts:":["1f49e"],":vhs:":["1f4fc"],":arrows_clockwise:":["1f503"],":heart_decoration:":["1f49f"],":loud_sound:":["1f50a"],":battery:":["1f50b"],":diamond_shape_with_a_dot_inside:":["1f4a0"],":electric_plug:":["1f50c"],":mag:":["1f50d"],":bulb:":["1f4a1"],":mag_right:":["1f50e"],":lock_with_ink_pen:":["1f50f"],":anger:":["1f4a2"],":closed_lock_with_key:":["1f510"],":key:":["1f511"],":bomb:":["1f4a3"],":lock:":["1f512"],":unlock:":["1f513"],":zzz:":["1f4a4"],":bell:":["1f514"],":bookmark:":["1f516"],":boom:":["1f4a5"],":link:":["1f517"],":radio_button:":["1f518"],":sweat_drops:":["1f4a6"],":back:":["1f519"],":end:":["1f51a"],":droplet:":["1f4a7"],":on:":["1f51b"],":soon:":["1f51c"],":dash:":["1f4a8"],":top:":["1f51d"],":underage:":["1f51e"],":poop:":["1f4a9"],":shit:":["1f4a9"],":hankey:":["1f4a9"],":poo:":["1f4a9"],":keycap_ten:":["1f51f"],":muscle:":["1f4aa"],":capital_abcd:":["1f520"],":abcd:":["1f521"],":dizzy:":["1f4ab"],":1234:":["1f522"],":symbols:":["1f523"],":speech_balloon:":["1f4ac"],":abc:":["1f524"],":fire:":["1f525"],":flame:":["1f525"],":white_flower:":["1f4ae"],":flashlight:":["1f526"],":wrench:":["1f527"],":100:":["1f4af"],":hammer:":["1f528"],":nut_and_bolt:":["1f529"],":moneybag:":["1f4b0"],":knife:":["1f52a"],":gun:":["1f52b"],":currency_exchange:":["1f4b1"],":crystal_ball:":["1f52e"],":heavy_dollar_sign:":["1f4b2"],":six_pointed_star:":["1f52f"],":credit_card:":["1f4b3"],":beginner:":["1f530"],":trident:":["1f531"],":yen:":["1f4b4"],":black_square_button:":["1f532"],":white_square_button:":["1f533"],":dollar:":["1f4b5"],":red_circle:":["1f534"],":large_blue_circle:":["1f535"],":money_with_wings:":["1f4b8"],":large_orange_diamond:":["1f536"],":large_blue_diamond:":["1f537"],":chart:":["1f4b9"],":small_orange_diamond:":["1f538"],":small_blue_diamond:":["1f539"],":seat:":["1f4ba"],":small_red_triangle:":["1f53a"],":small_red_triangle_down:":["1f53b"],":computer:":["1f4bb"],":arrow_up_small:":["1f53c"],":briefcase:":["1f4bc"],":arrow_down_small:":["1f53d"],":clock1:":["1f550"],":minidisc:":["1f4bd"],":clock2:":["1f551"],":floppy_disk:":["1f4be"],":clock3:":["1f552"],":cd:":["1f4bf"],":clock4:":["1f553"],":dvd:":["1f4c0"],":clock5:":["1f554"],":clock6:":["1f555"],":file_folder:":["1f4c1"],":clock7:":["1f556"],":clock8:":["1f557"],":open_file_folder:":["1f4c2"],":clock9:":["1f558"],":clock10:":["1f559"],":page_with_curl:":["1f4c3"],":clock11:":["1f55a"],":clock12:":["1f55b"],":page_facing_up:":["1f4c4"],":mount_fuji:":["1f5fb"],":tokyo_tower:":["1f5fc"],":date:":["1f4c5"],":statue_of_liberty:":["1f5fd"],":japan:":["1f5fe"],":calendar:":["1f4c6"],":moyai:":["1f5ff"],":grin:":["1f601"],":joy:":["1f602"],":smiley:":["1f603"],":chart_with_upwards_trend:":["1f4c8"],":smile:":["1f604"],":sweat_smile:":["1f605"],":chart_with_downwards_trend:":["1f4c9"],":laughing:":["1f606"],":satisfied:":["1f606"],":wink:":["1f609"],":bar_chart:":["1f4ca"],":blush:":["1f60a"],":yum:":["1f60b"],":clipboard:":["1f4cb"],":relieved:":["1f60c"],":heart_eyes:":["1f60d"],":pushpin:":["1f4cc"],":smirk:":["1f60f"],":unamused:":["1f612"],":round_pushpin:":["1f4cd"],":sweat:":["1f613"],":pensive:":["1f614"],":paperclip:":["1f4ce"],":confounded:":["1f616"],":kissing_heart:":["1f618"],":straight_ruler:":["1f4cf"],":kissing_closed_eyes:":["1f61a"],":stuck_out_tongue_winking_eye:":["1f61c"],":triangular_ruler:":["1f4d0"],":stuck_out_tongue_closed_eyes:":["1f61d"],":disappointed:":["1f61e"],":bookmark_tabs:":["1f4d1"],":angry:":["1f620"],":rage:":["1f621"],":cry:":["1f622"],":persevere:":["1f623"],":triumph:":["1f624"],":disappointed_relieved:":["1f625"],":fearful:":["1f628"],":weary:":["1f629"],":sleepy:":["1f62a"],":tired_face:":["1f62b"],":sob:":["1f62d"],":cold_sweat:":["1f630"],":scream:":["1f631"],":astonished:":["1f632"],":flushed:":["1f633"],":dizzy_face:":["1f635"],":mask:":["1f637"],":smile_cat:":["1f638"],":joy_cat:":["1f639"],":smiley_cat:":["1f63a"],":heart_eyes_cat:":["1f63b"],":smirk_cat:":["1f63c"],":kissing_cat:":["1f63d"],":pouting_cat:":["1f63e"],":crying_cat_face:":["1f63f"],":scream_cat:":["1f640"],":no_good:":["1f645"],":ok_woman:":["1f646"],":bow:":["1f647"],":see_no_evil:":["1f648"],":hear_no_evil:":["1f649"],":speak_no_evil:":["1f64a"],":raising_hand:":["1f64b"],":raised_hands:":["1f64c"],":person_frowning:":["1f64d"],":person_with_pouting_face:":["1f64e"],":pray:":["1f64f"],":rocket:":["1f680"],":railway_car:":["1f683"],":bullettrain_side:":["1f684"],":bullettrain_front:":["1f685"],":metro:":["1f687"],":station:":["1f689"],":bus:":["1f68c"],":busstop:":["1f68f"],":ambulance:":["1f691"],":fire_engine:":["1f692"],":police_car:":["1f693"],":taxi:":["1f695"],":red_car:":["1f697"],":blue_car:":["1f699"],":truck:":["1f69a"],":ship:":["1f6a2"],":speedboat:":["1f6a4"],":traffic_light:":["1f6a5"],":construction:":["1f6a7"],":rotating_light:":["1f6a8"],":triangular_flag_on_post:":["1f6a9"],":door:":["1f6aa"],":no_entry_sign:":["1f6ab"],":smoking:":["1f6ac"],":no_smoking:":["1f6ad"],":bike:":["1f6b2"],":walking:":["1f6b6"],":mens:":["1f6b9"],":womens:":["1f6ba"],":restroom:":["1f6bb"],":baby_symbol:":["1f6bc"],":toilet:":["1f6bd"],":wc:":["1f6be"],":bath:":["1f6c0"],":grinning:":["1f600"],":innocent:":["1f607"],":smiling_imp:":["1f608"],":sunglasses:":["1f60e"],":neutral_face:":["1f610"],":expressionless:":["1f611"],":confused:":["1f615"],":kissing:":["1f617"],":kissing_smiling_eyes:":["1f619"],":stuck_out_tongue:":["1f61b"],":worried:":["1f61f"],":frowning:":["1f626"],":anguished:":["1f627"],":grimacing:":["1f62c"],":open_mouth:":["1f62e"],":hushed:":["1f62f"],":sleeping:":["1f634"],":no_mouth:":["1f636"],":helicopter:":["1f681"],":steam_locomotive:":["1f682"],":train2:":["1f686"],":light_rail:":["1f688"],":tram:":["1f68a"],":oncoming_bus:":["1f68d"],":trolleybus:":["1f68e"],":minibus:":["1f690"],":oncoming_police_car:":["1f694"],":oncoming_taxi:":["1f696"],":oncoming_automobile:":["1f698"],":articulated_lorry:":["1f69b"],":tractor:":["1f69c"],":monorail:":["1f69d"],":mountain_railway:":["1f69e"],":suspension_railway:":["1f69f"],":mountain_cableway:":["1f6a0"],":aerial_tramway:":["1f6a1"],":rowboat:":["1f6a3"],":vertical_traffic_light:":["1f6a6"],":put_litter_in_its_place:":["1f6ae"],":do_not_litter:":["1f6af"],":potable_water:":["1f6b0"],":non-potable_water:":["1f6b1"],":no_bicycles:":["1f6b3"],":bicyclist:":["1f6b4"],":mountain_bicyclist:":["1f6b5"],":no_pedestrians:":["1f6b7"],":children_crossing:":["1f6b8"],":shower:":["1f6bf"],":bathtub:":["1f6c1"],":passport_control:":["1f6c2"],":customs:":["1f6c3"],":baggage_claim:":["1f6c4"],":left_luggage:":["1f6c5"],":earth_africa:":["1f30d"],":earth_americas:":["1f30e"],":globe_with_meridians:":["1f310"],":waxing_crescent_moon:":["1f312"],":waning_gibbous_moon:":["1f316"],":last_quarter_moon:":["1f317"],":waning_crescent_moon:":["1f318"],":new_moon_with_face:":["1f31a"],":last_quarter_moon_with_face:":["1f31c"],":full_moon_with_face:":["1f31d"],":sun_with_face:":["1f31e"],":evergreen_tree:":["1f332"],":deciduous_tree:":["1f333"],":lemon:":["1f34b"],":pear:":["1f350"],":baby_bottle:":["1f37c"],":horse_racing:":["1f3c7"],":rugby_football:":["1f3c9"],":european_post_office:":["1f3e4"],":rat:":["1f400"],":mouse2:":["1f401"],":ox:":["1f402"],":water_buffalo:":["1f403"],":cow2:":["1f404"],":tiger2:":["1f405"],":leopard:":["1f406"],":rabbit2:":["1f407"],":cat2:":["1f408"],":dragon:":["1f409"],":crocodile:":["1f40a"],":whale2:":["1f40b"],":ram:":["1f40f"],":goat:":["1f410"],":rooster:":["1f413"],":dog2:":["1f415"],":pig2:":["1f416"],":dromedary_camel:":["1f42a"],":busts_in_silhouette:":["1f465"],":two_men_holding_hands:":["1f46c"],":two_women_holding_hands:":["1f46d"],":thought_balloon:":["1f4ad"],":euro:":["1f4b6"],":pound:":["1f4b7"],":mailbox_with_mail:":["1f4ec"],":mailbox_with_no_mail:":["1f4ed"],":postal_horn:":["1f4ef"],":no_mobile_phones:":["1f4f5"],":twisted_rightwards_arrows:":["1f500"],":repeat:":["1f501"],":repeat_one:":["1f502"],":arrows_counterclockwise:":["1f504"],":low_brightness:":["1f505"],":high_brightness:":["1f506"],":mute:":["1f507"],":sound:":["1f509"],":no_bell:":["1f515"],":microscope:":["1f52c"],":telescope:":["1f52d"],":clock130:":["1f55c"],":clock230:":["1f55d"],":clock330:":["1f55e"],":clock430:":["1f55f"],":clock530:":["1f560"],":clock630:":["1f561"],":clock730:":["1f562"],":clock830:":["1f563"],":clock930:":["1f564"],":clock1030:":["1f565"],":clock1130:":["1f566"],":clock1230:":["1f567"],":speaker:":["1f508"],":train:":["1f68b"],":loop:":["27bf"],":af:":["1f1e6-1f1eb"],":al:":["1f1e6-1f1f1"],":dz:":["1f1e9-1f1ff"],":ad:":["1f1e6-1f1e9"],":ao:":["1f1e6-1f1f4"],":ag:":["1f1e6-1f1ec"],":ar:":["1f1e6-1f1f7"],":am:":["1f1e6-1f1f2"],":au:":["1f1e6-1f1fa"],":at:":["1f1e6-1f1f9"],":az:":["1f1e6-1f1ff"],":bs:":["1f1e7-1f1f8"],":bh:":["1f1e7-1f1ed"],":bd:":["1f1e7-1f1e9"],":bb:":["1f1e7-1f1e7"],":by:":["1f1e7-1f1fe"],":be:":["1f1e7-1f1ea"],":bz:":["1f1e7-1f1ff"],":bj:":["1f1e7-1f1ef"],":bt:":["1f1e7-1f1f9"],":bo:":["1f1e7-1f1f4"],":ba:":["1f1e7-1f1e6"],":bw:":["1f1e7-1f1fc"],":br:":["1f1e7-1f1f7"],":bn:":["1f1e7-1f1f3"],":bg:":["1f1e7-1f1ec"],":bf:":["1f1e7-1f1eb"],":bi:":["1f1e7-1f1ee"],":kh:":["1f1f0-1f1ed"],":cm:":["1f1e8-1f1f2"],":ca:":["1f1e8-1f1e6"],":cv:":["1f1e8-1f1fb"],":cf:":["1f1e8-1f1eb"],":td:":["1f1f9-1f1e9"],":chile:":["1f1e8-1f1f1"],":co:":["1f1e8-1f1f4"],":km:":["1f1f0-1f1f2"],":cr:":["1f1e8-1f1f7"],":ci:":["1f1e8-1f1ee"],":hr:":["1f1ed-1f1f7"],":cu:":["1f1e8-1f1fa"],":cy:":["1f1e8-1f1fe"],":cz:":["1f1e8-1f1ff"],":congo:":["1f1e8-1f1e9"],":dk:":["1f1e9-1f1f0"],":dj:":["1f1e9-1f1ef"],":dm:":["1f1e9-1f1f2"],":do:":["1f1e9-1f1f4"],":tl:":["1f1f9-1f1f1"],":ec:":["1f1ea-1f1e8"],":eg:":["1f1ea-1f1ec"],":sv:":["1f1f8-1f1fb"],":gq:":["1f1ec-1f1f6"],":er:":["1f1ea-1f1f7"],":ee:":["1f1ea-1f1ea"],":et:":["1f1ea-1f1f9"],":fj:":["1f1eb-1f1ef"],":fi:":["1f1eb-1f1ee"],":ga:":["1f1ec-1f1e6"],":gm:":["1f1ec-1f1f2"],":ge:":["1f1ec-1f1ea"],":gh:":["1f1ec-1f1ed"],":gr:":["1f1ec-1f1f7"],":gd:":["1f1ec-1f1e9"],":gt:":["1f1ec-1f1f9"],":gn:":["1f1ec-1f1f3"],":gw:":["1f1ec-1f1fc"],":gy:":["1f1ec-1f1fe"],":ht:":["1f1ed-1f1f9"],":hn:":["1f1ed-1f1f3"],":hu:":["1f1ed-1f1fa"],":is:":["1f1ee-1f1f8"],":in:":["1f1ee-1f1f3"],":indonesia:":["1f1ee-1f1e9"],":ir:":["1f1ee-1f1f7"],":iq:":["1f1ee-1f1f6"],":ie:":["1f1ee-1f1ea"],":il:":["1f1ee-1f1f1"],":jm:":["1f1ef-1f1f2"],":jo:":["1f1ef-1f1f4"],":kz:":["1f1f0-1f1ff"],":ke:":["1f1f0-1f1ea"],":ki:":["1f1f0-1f1ee"],":xk:":["1f1fd-1f1f0"],":kw:":["1f1f0-1f1fc"],":kg:":["1f1f0-1f1ec"],":la:":["1f1f1-1f1e6"],":lv:":["1f1f1-1f1fb"],":lb:":["1f1f1-1f1e7"],":ls:":["1f1f1-1f1f8"],":lr:":["1f1f1-1f1f7"],":ly:":["1f1f1-1f1fe"],":li:":["1f1f1-1f1ee"],":lt:":["1f1f1-1f1f9"],":lu:":["1f1f1-1f1fa"],":mk:":["1f1f2-1f1f0"],":mg:":["1f1f2-1f1ec"],":mw:":["1f1f2-1f1fc"],":my:":["1f1f2-1f1fe"],":mv:":["1f1f2-1f1fb"],":ml:":["1f1f2-1f1f1"],":mt:":["1f1f2-1f1f9"],":mh:":["1f1f2-1f1ed"],":mr:":["1f1f2-1f1f7"],":mu:":["1f1f2-1f1fa"],":mx:":["1f1f2-1f1fd"],":fm:":["1f1eb-1f1f2"],":md:":["1f1f2-1f1e9"],":mc:":["1f1f2-1f1e8"],":mn:":["1f1f2-1f1f3"],":me:":["1f1f2-1f1ea"],":ma:":["1f1f2-1f1e6"],":mz:":["1f1f2-1f1ff"],":mm:":["1f1f2-1f1f2"],":na:":["1f1f3-1f1e6"],":nr:":["1f1f3-1f1f7"],":np:":["1f1f3-1f1f5"],":nl:":["1f1f3-1f1f1"],":nz:":["1f1f3-1f1ff"],":ni:":["1f1f3-1f1ee"],":ne:":["1f1f3-1f1ea"],":nigeria:":["1f1f3-1f1ec"],":kp:":["1f1f0-1f1f5"],":no:":["1f1f3-1f1f4"],":om:":["1f1f4-1f1f2"],":pk:":["1f1f5-1f1f0"],":pw:":["1f1f5-1f1fc"],":pa:":["1f1f5-1f1e6"],":pg:":["1f1f5-1f1ec"],":py:":["1f1f5-1f1fe"],":pe:":["1f1f5-1f1ea"],":ph:":["1f1f5-1f1ed"],":pl:":["1f1f5-1f1f1"],":pt:":["1f1f5-1f1f9"],":qa:":["1f1f6-1f1e6"],":tw:":["1f1f9-1f1fc"],":cg:":["1f1e8-1f1ec"],":ro:":["1f1f7-1f1f4"],":rw:":["1f1f7-1f1fc"],":kn:":["1f1f0-1f1f3"],":lc:":["1f1f1-1f1e8"],":vc:":["1f1fb-1f1e8"],":ws:":["1f1fc-1f1f8"],":sm:":["1f1f8-1f1f2"],":st:":["1f1f8-1f1f9"],":saudiarabia:":["1f1f8-1f1e6"],":saudi:":["1f1f8-1f1e6"],":sn:":["1f1f8-1f1f3"],":rs:":["1f1f7-1f1f8"],":sc:":["1f1f8-1f1e8"],":sl:":["1f1f8-1f1f1"],":sg:":["1f1f8-1f1ec"],":sk:":["1f1f8-1f1f0"],":si:":["1f1f8-1f1ee"],":sb:":["1f1f8-1f1e7"],":so:":["1f1f8-1f1f4"],":za:":["1f1ff-1f1e6"],":lk:":["1f1f1-1f1f0"],":sd:":["1f1f8-1f1e9"],":sr:":["1f1f8-1f1f7"],":sz:":["1f1f8-1f1ff"],":se:":["1f1f8-1f1ea"],":ch:":["1f1e8-1f1ed"],":sy:":["1f1f8-1f1fe"],":tj:":["1f1f9-1f1ef"],":tz:":["1f1f9-1f1ff"],":th:":["1f1f9-1f1ed"],":tg:":["1f1f9-1f1ec"],":to:":["1f1f9-1f1f4"],":tt:":["1f1f9-1f1f9"],":tn:":["1f1f9-1f1f3"],":tr:":["1f1f9-1f1f7"],":turkmenistan:":["1f1f9-1f1f2"],":tuvalu:":["1f1f9-1f1fb"],":ug:":["1f1fa-1f1ec"],":ua:":["1f1fa-1f1e6"],":ae:":["1f1e6-1f1ea"],":uy:":["1f1fa-1f1fe"],":uz:":["1f1fa-1f1ff"],":vu:":["1f1fb-1f1fa"],":va:":["1f1fb-1f1e6"],":ve:":["1f1fb-1f1ea"],":vn:":["1f1fb-1f1f3"],":eh:":["1f1ea-1f1ed"],":ye:":["1f1fe-1f1ea"],":zm:":["1f1ff-1f1f2"],":zw:":["1f1ff-1f1fc"],":pr:":["1f1f5-1f1f7"],":ky:":["1f1f0-1f1fe"],":bm:":["1f1e7-1f1f2"],":pf:":["1f1f5-1f1eb"],":ps:":["1f1f5-1f1f8"],":nc:":["1f1f3-1f1e8"],":sh:":["1f1f8-1f1ed"],":aw:":["1f1e6-1f1fc"],":vi:":["1f1fb-1f1ee"],":hk:":["1f1ed-1f1f0"],":ac:":["1f1e6-1f1e8"],":ms:":["1f1f2-1f1f8"],":gu:":["1f1ec-1f1fa"],":gl:":["1f1ec-1f1f1"],":nu:":["1f1f3-1f1fa"],":wf:":["1f1fc-1f1eb"],":mo:":["1f1f2-1f1f4"],":fo:":["1f1eb-1f1f4"],":fk:":["1f1eb-1f1f0"],":je:":["1f1ef-1f1ea"],":ai:":["1f1e6-1f1ee"],":gi:":["1f1ec-1f1ee"]},a.asciiList={"<3":"2764","</3":"1f494",":')":"1f602",":'-)":"1f602",":D":"1f603",":-D":"1f603","=D":"1f603",":)":"1f604",":-)":"1f604","=]":"1f604","=)":"1f604",":]":"1f604","':)":"1f605","':-)":"1f605","'=)":"1f605","':D":"1f605","':-D":"1f605","'=D":"1f605",">:)":"1f606",">;)":"1f606",">:-)":"1f606",">=)":"1f606",";)":"1f609",";-)":"1f609","*-)":"1f609","*)":"1f609",";-]":"1f609",";]":"1f609",";D":"1f609",";^)":"1f609","':(":"1f613","':-(":"1f613","'=(":"1f613",":*":"1f618",":-*":"1f618","=*":"1f618",":^*":"1f618",">:P":"1f61c","X-P":"1f61c","x-p":"1f61c",">:[":"1f61e",":-(":"1f61e",":(":"1f61e",":-[":"1f61e",":[":"1f61e","=(":"1f61e",">:(":"1f620",">:-(":"1f620",":@":"1f620",":'(":"1f622",":'-(":"1f622",";(":"1f622",";-(":"1f622",">.<":"1f623",":$":"1f633","=$":"1f633","#-)":"1f635","#)":"1f635","%-)":"1f635","%)":"1f635","X)":"1f635","X-)":"1f635","*\\0/*":"1f646","\\0/":"1f646","*\\O/*":"1f646","\\O/":"1f646","O:-)":"1f607","0:-3":"1f607","0:3":"1f607","0:-)":"1f607","0:)":"1f607","0;^)":"1f607","O:)":"1f607","O;-)":"1f607","O=)":"1f607","0;-)":"1f607","O:-3":"1f607","O:3":"1f607","B-)":"1f60e","B)":"1f60e","8)":"1f60e","8-)":"1f60e","B-D":"1f60e","8-D":"1f60e","-_-":"1f611","-__-":"1f611","-___-":"1f611",">:\\":"1f615",">:/":"1f615",":-/":"1f615",":-.":"1f615",":/":"1f615",":\\":"1f615","=/":"1f615","=\\":"1f615",":L":"1f615","=L":"1f615",":P":"1f61b",":-P":"1f61b","=P":"1f61b",":-p":"1f61b",":p":"1f61b","=p":"1f61b",":-Þ":"1f61b",":Þ":"1f61b",":þ":"1f61b",":-þ":"1f61b",":-b":"1f61b",":b":"1f61b","d:":"1f61b",":-O":"1f62e",":O":"1f62e",":-o":"1f62e",":o":"1f62e",O_O:"1f62e",">:O":"1f62e",":-X":"1f636",":X":"1f636",":-#":"1f636",":#":"1f636","=X":"1f636","=x":"1f636",":x":"1f636",":-x":"1f636","=#":"1f636"},a.asciiRegexp="(\\<3|<3|\\<\\/3|<\\/3|\\:'\\)|\\:'\\-\\)|\\:D|\\:\\-D|\\=D|\\:\\)|\\:\\-\\)|\\=\\]|\\=\\)|\\:\\]|'\\:\\)|'\\:\\-\\)|'\\=\\)|'\\:D|'\\:\\-D|'\\=D|\\>\\:\\)|>\\:\\)|\\>;\\)|>;\\)|\\>\\:\\-\\)|>\\:\\-\\)|\\>\\=\\)|>\\=\\)|;\\)|;\\-\\)|\\*\\-\\)|\\*\\)|;\\-\\]|;\\]|;D|;\\^\\)|'\\:\\(|'\\:\\-\\(|'\\=\\(|\\:\\*|\\:\\-\\*|\\=\\*|\\:\\^\\*|\\>\\:P|>\\:P|X\\-P|x\\-p|\\>\\:\\[|>\\:\\[|\\:\\-\\(|\\:\\(|\\:\\-\\[|\\:\\[|\\=\\(|\\>\\:\\(|>\\:\\(|\\>\\:\\-\\(|>\\:\\-\\(|\\:@|\\:'\\(|\\:'\\-\\(|;\\(|;\\-\\(|\\>\\.\\<|>\\.<|\\:\\$|\\=\\$|#\\-\\)|#\\)|%\\-\\)|%\\)|X\\)|X\\-\\)|\\*\\\\0\\/\\*|\\\\0\\/|\\*\\\\O\\/\\*|\\\\O\\/|O\\:\\-\\)|0\\:\\-3|0\\:3|0\\:\\-\\)|0\\:\\)|0;\\^\\)|O\\:\\-\\)|O\\:\\)|O;\\-\\)|O\\=\\)|0;\\-\\)|O\\:\\-3|O\\:3|B\\-\\)|B\\)|8\\)|8\\-\\)|B\\-D|8\\-D|\\-_\\-|\\-__\\-|\\-___\\-|\\>\\:\\\\|>\\:\\\\|\\>\\:\\/|>\\:\\/|\\:\\-\\/|\\:\\-\\.|\\:\\/|\\:\\\\|\\=\\/|\\=\\\\|\\:L|\\=L|\\:P|\\:\\-P|\\=P|\\:\\-p|\\:p|\\=p|\\:\\-Þ|\\:\\-Þ|\\:Þ|\\:Þ|\\:þ|\\:þ|\\:\\-þ|\\:\\-þ|\\:\\-b|\\:b|d\\:|\\:\\-O|\\:O|\\:\\-o|\\:o|O_O|\\>\\:O|>\\:O|\\:\\-X|\\:X|\\:\\-#|\\:#|\\=X|\\=x|\\:x|\\:\\-x|\\=#)",a.unicodeRegexp="(#\\uFE0F\\u20E3|#\\u20E3|0\\uFE0F\\u20E3|0\\u20E3|1\\uFE0F\\u20E3|1\\u20E3|2\\uFE0F\\u20E3|2\\u20E3|3\\uFE0F\\u20E3|3\\u20E3|4\\uFE0F\\u20E3|4\\u20E3|5\\uFE0F\\u20E3|5\\u20E3|6\\uFE0F\\u20E3|6\\u20E3|7\\uFE0F\\u20E3|7\\u20E3|8\\uFE0F\\u20E3|8\\u20E3|9\\uFE0F\\u20E3|9\\u20E3|\\u00A9|\\u00AE|\\u203C\\uFE0F|\\u203C|\\u2049\\uFE0F|\\u2049|\\u2122|\\u2139\\uFE0F|\\u2139|\\u2194\\uFE0F|\\u2194|\\u2195\\uFE0F|\\u2195|\\u2196\\uFE0F|\\u2196|\\u2197\\uFE0F|\\u2197|\\u2198\\uFE0F|\\u2198|\\u2199\\uFE0F|\\u2199|\\u21A9\\uFE0F|\\u21A9|\\u21AA\\uFE0F|\\u21AA|\\u231A\\uFE0F|\\u231A|\\u231B\\uFE0F|\\u231B|\\u23E9|\\u23EA|\\u23EB|\\u23EC|\\u23F0|\\u23F3|\\u24C2\\uFE0F|\\u24C2|\\u25AA\\uFE0F|\\u25AA|\\u25AB\\uFE0F|\\u25AB|\\u25B6\\uFE0F|\\u25B6|\\u25C0\\uFE0F|\\u25C0|\\u25FB\\uFE0F|\\u25FB|\\u25FC\\uFE0F|\\u25FC|\\u25FD\\uFE0F|\\u25FD|\\u25FE\\uFE0F|\\u25FE|\\u2600\\uFE0F|\\u2600|\\u2601\\uFE0F|\\u2601|\\u260E\\uFE0F|\\u260E|\\u2611\\uFE0F|\\u2611|\\u2614\\uFE0F|\\u2614|\\u2615\\uFE0F|\\u2615|\\u261D\\uFE0F|\\u261D|\\u263A\\uFE0F|\\u263A|\\u2648\\uFE0F|\\u2648|\\u2649\\uFE0F|\\u2649|\\u264A\\uFE0F|\\u264A|\\u264B\\uFE0F|\\u264B|\\u264C\\uFE0F|\\u264C|\\u264D\\uFE0F|\\u264D|\\u264E\\uFE0F|\\u264E|\\u264F\\uFE0F|\\u264F|\\u2650\\uFE0F|\\u2650|\\u2651\\uFE0F|\\u2651|\\u2652\\uFE0F|\\u2652|\\u2653\\uFE0F|\\u2653|\\u2660\\uFE0F|\\u2660|\\u2663\\uFE0F|\\u2663|\\u2665\\uFE0F|\\u2665|\\u2666\\uFE0F|\\u2666|\\u2668\\uFE0F|\\u2668|\\u267B\\uFE0F|\\u267B|\\u267F\\uFE0F|\\u267F|\\u2693\\uFE0F|\\u2693|\\u26A0\\uFE0F|\\u26A0|\\u26A1\\uFE0F|\\u26A1|\\u26AA\\uFE0F|\\u26AA|\\u26AB\\uFE0F|\\u26AB|\\u26BD\\uFE0F|\\u26BD|\\u26BE\\uFE0F|\\u26BE|\\u26C4\\uFE0F|\\u26C4|\\u26C5\\uFE0F|\\u26C5|\\u26CE|\\u26D4\\uFE0F|\\u26D4|\\u26EA\\uFE0F|\\u26EA|\\u26F2\\uFE0F|\\u26F2|\\u26F3\\uFE0F|\\u26F3|\\u26F5\\uFE0F|\\u26F5|\\u26FA\\uFE0F|\\u26FA|\\u26FD\\uFE0F|\\u26FD|\\u2702\\uFE0F|\\u2702|\\u2705|\\u2708\\uFE0F|\\u2708|\\u2709\\uFE0F|\\u2709|\\u270A|\\u270B|\\u270C\\uFE0F|\\u270C|\\u270F\\uFE0F|\\u270F|\\u2712\\uFE0F|\\u2712|\\u2714\\uFE0F|\\u2714|\\u2716\\uFE0F|\\u2716|\\u2728|\\u2733\\uFE0F|\\u2733|\\u2734\\uFE0F|\\u2734|\\u2744\\uFE0F|\\u2744|\\u2747\\uFE0F|\\u2747|\\u274C|\\u274E|\\u2753|\\u2754|\\u2755|\\u2757\\uFE0F|\\u2757|\\u2764\\uFE0F|\\u2764|\\u2795|\\u2796|\\u2797|\\u27A1\\uFE0F|\\u27A1|\\u27B0|\\u2934\\uFE0F|\\u2934|\\u2935\\uFE0F|\\u2935|\\u2B05\\uFE0F|\\u2B05|\\u2B06\\uFE0F|\\u2B06|\\u2B07\\uFE0F|\\u2B07|\\u2B1B\\uFE0F|\\u2B1B|\\u2B1C\\uFE0F|\\u2B1C|\\u2B50\\uFE0F|\\u2B50|\\u2B55\\uFE0F|\\u2B55|\\u3030|\\u303D\\uFE0F|\\u303D|\\u3297\\uFE0F|\\u3297|\\u3299\\uFE0F|\\u3299|\\uD83C\\uDC04\\uFE0F|\\uD83C\\uDC04|\\uD83C\\uDCCF|\\uD83C\\uDD70|\\uD83C\\uDD71|\\uD83C\\uDD7E|\\uD83C\\uDD7F\\uFE0F|\\uD83C\\uDD7F|\\uD83C\\uDD8E|\\uD83C\\uDD91|\\uD83C\\uDD92|\\uD83C\\uDD93|\\uD83C\\uDD94|\\uD83C\\uDD95|\\uD83C\\uDD96|\\uD83C\\uDD97|\\uD83C\\uDD98|\\uD83C\\uDD99|\\uD83C\\uDD9A|\\uD83C\\uDDE8\\uD83C\\uDDF3|\\uD83C\\uDDE9\\uD83C\\uDDEA|\\uD83C\\uDDEA\\uD83C\\uDDF8|\\uD83C\\uDDEB\\uD83C\\uDDF7|\\uD83C\\uDDEC\\uD83C\\uDDE7|\\uD83C\\uDDEE\\uD83C\\uDDF9|\\uD83C\\uDDEF\\uD83C\\uDDF5|\\uD83C\\uDDF0\\uD83C\\uDDF7|\\uD83C\\uDDFA\\uD83C\\uDDF8|\\uD83C\\uDDF7\\uD83C\\uDDFA|\\uD83C\\uDE01|\\uD83C\\uDE02|\\uD83C\\uDE1A\\uFE0F|\\uD83C\\uDE1A|\\uD83C\\uDE2F\\uFE0F|\\uD83C\\uDE2F|\\uD83C\\uDE32|\\uD83C\\uDE33|\\uD83C\\uDE34|\\uD83C\\uDE35|\\uD83C\\uDE36|\\uD83C\\uDE37|\\uD83C\\uDE38|\\uD83C\\uDE39|\\uD83C\\uDE3A|\\uD83C\\uDE50|\\uD83C\\uDE51|\\uD83C\\uDF00|\\uD83C\\uDF01|\\uD83C\\uDF02|\\uD83C\\uDF03|\\uD83C\\uDF04|\\uD83C\\uDF05|\\uD83C\\uDF06|\\uD83C\\uDF07|\\uD83C\\uDF08|\\uD83C\\uDF09|\\uD83C\\uDF0A|\\uD83C\\uDF0B|\\uD83C\\uDF0C|\\uD83C\\uDF0F|\\uD83C\\uDF11|\\uD83C\\uDF13|\\uD83C\\uDF14|\\uD83C\\uDF15|\\uD83C\\uDF19|\\uD83C\\uDF1B|\\uD83C\\uDF1F|\\uD83C\\uDF20|\\uD83C\\uDF30|\\uD83C\\uDF31|\\uD83C\\uDF34|\\uD83C\\uDF35|\\uD83C\\uDF37|\\uD83C\\uDF38|\\uD83C\\uDF39|\\uD83C\\uDF3A|\\uD83C\\uDF3B|\\uD83C\\uDF3C|\\uD83C\\uDF3D|\\uD83C\\uDF3E|\\uD83C\\uDF3F|\\uD83C\\uDF40|\\uD83C\\uDF41|\\uD83C\\uDF42|\\uD83C\\uDF43|\\uD83C\\uDF44|\\uD83C\\uDF45|\\uD83C\\uDF46|\\uD83C\\uDF47|\\uD83C\\uDF48|\\uD83C\\uDF49|\\uD83C\\uDF4A|\\uD83C\\uDF4C|\\uD83C\\uDF4D|\\uD83C\\uDF4E|\\uD83C\\uDF4F|\\uD83C\\uDF51|\\uD83C\\uDF52|\\uD83C\\uDF53|\\uD83C\\uDF54|\\uD83C\\uDF55|\\uD83C\\uDF56|\\uD83C\\uDF57|\\uD83C\\uDF58|\\uD83C\\uDF59|\\uD83C\\uDF5A|\\uD83C\\uDF5B|\\uD83C\\uDF5C|\\uD83C\\uDF5D|\\uD83C\\uDF5E|\\uD83C\\uDF5F|\\uD83C\\uDF60|\\uD83C\\uDF61|\\uD83C\\uDF62|\\uD83C\\uDF63|\\uD83C\\uDF64|\\uD83C\\uDF65|\\uD83C\\uDF66|\\uD83C\\uDF67|\\uD83C\\uDF68|\\uD83C\\uDF69|\\uD83C\\uDF6A|\\uD83C\\uDF6B|\\uD83C\\uDF6C|\\uD83C\\uDF6D|\\uD83C\\uDF6E|\\uD83C\\uDF6F|\\uD83C\\uDF70|\\uD83C\\uDF71|\\uD83C\\uDF72|\\uD83C\\uDF73|\\uD83C\\uDF74|\\uD83C\\uDF75|\\uD83C\\uDF76|\\uD83C\\uDF77|\\uD83C\\uDF78|\\uD83C\\uDF79|\\uD83C\\uDF7A|\\uD83C\\uDF7B|\\uD83C\\uDF80|\\uD83C\\uDF81|\\uD83C\\uDF82|\\uD83C\\uDF83|\\uD83C\\uDF84|\\uD83C\\uDF85|\\uD83C\\uDF86|\\uD83C\\uDF87|\\uD83C\\uDF88|\\uD83C\\uDF89|\\uD83C\\uDF8A|\\uD83C\\uDF8B|\\uD83C\\uDF8C|\\uD83C\\uDF8D|\\uD83C\\uDF8E|\\uD83C\\uDF8F|\\uD83C\\uDF90|\\uD83C\\uDF91|\\uD83C\\uDF92|\\uD83C\\uDF93|\\uD83C\\uDFA0|\\uD83C\\uDFA1|\\uD83C\\uDFA2|\\uD83C\\uDFA3|\\uD83C\\uDFA4|\\uD83C\\uDFA5|\\uD83C\\uDFA6|\\uD83C\\uDFA7|\\uD83C\\uDFA8|\\uD83C\\uDFA9|\\uD83C\\uDFAA|\\uD83C\\uDFAB|\\uD83C\\uDFAC|\\uD83C\\uDFAD|\\uD83C\\uDFAE|\\uD83C\\uDFAF|\\uD83C\\uDFB0|\\uD83C\\uDFB1|\\uD83C\\uDFB2|\\uD83C\\uDFB3|\\uD83C\\uDFB4|\\uD83C\\uDFB5|\\uD83C\\uDFB6|\\uD83C\\uDFB7|\\uD83C\\uDFB8|\\uD83C\\uDFB9|\\uD83C\\uDFBA|\\uD83C\\uDFBB|\\uD83C\\uDFBC|\\uD83C\\uDFBD|\\uD83C\\uDFBE|\\uD83C\\uDFBF|\\uD83C\\uDFC0|\\uD83C\\uDFC1|\\uD83C\\uDFC2|\\uD83C\\uDFC3|\\uD83C\\uDFC4|\\uD83C\\uDFC6|\\uD83C\\uDFC8|\\uD83C\\uDFCA|\\uD83C\\uDFE0|\\uD83C\\uDFE1|\\uD83C\\uDFE2|\\uD83C\\uDFE3|\\uD83C\\uDFE5|\\uD83C\\uDFE6|\\uD83C\\uDFE7|\\uD83C\\uDFE8|\\uD83C\\uDFE9|\\uD83C\\uDFEA|\\uD83C\\uDFEB|\\uD83C\\uDFEC|\\uD83C\\uDFED|\\uD83C\\uDFEE|\\uD83C\\uDFEF|\\uD83C\\uDFF0|\\uD83D\\uDC0C|\\uD83D\\uDC0D|\\uD83D\\uDC0E|\\uD83D\\uDC11|\\uD83D\\uDC12|\\uD83D\\uDC14|\\uD83D\\uDC17|\\uD83D\\uDC18|\\uD83D\\uDC19|\\uD83D\\uDC1A|\\uD83D\\uDC1B|\\uD83D\\uDC1C|\\uD83D\\uDC1D|\\uD83D\\uDC1E|\\uD83D\\uDC1F|\\uD83D\\uDC20|\\uD83D\\uDC21|\\uD83D\\uDC22|\\uD83D\\uDC23|\\uD83D\\uDC24|\\uD83D\\uDC25|\\uD83D\\uDC26|\\uD83D\\uDC27|\\uD83D\\uDC28|\\uD83D\\uDC29|\\uD83D\\uDC2B|\\uD83D\\uDC2C|\\uD83D\\uDC2D|\\uD83D\\uDC2E|\\uD83D\\uDC2F|\\uD83D\\uDC30|\\uD83D\\uDC31|\\uD83D\\uDC32|\\uD83D\\uDC33|\\uD83D\\uDC34|\\uD83D\\uDC35|\\uD83D\\uDC36|\\uD83D\\uDC37|\\uD83D\\uDC38|\\uD83D\\uDC39|\\uD83D\\uDC3A|\\uD83D\\uDC3B|\\uD83D\\uDC3C|\\uD83D\\uDC3D|\\uD83D\\uDC3E|\\uD83D\\uDC40|\\uD83D\\uDC42|\\uD83D\\uDC43|\\uD83D\\uDC44|\\uD83D\\uDC45|\\uD83D\\uDC46|\\uD83D\\uDC47|\\uD83D\\uDC48|\\uD83D\\uDC49|\\uD83D\\uDC4A|\\uD83D\\uDC4B|\\uD83D\\uDC4C|\\uD83D\\uDC4D|\\uD83D\\uDC4E|\\uD83D\\uDC4F|\\uD83D\\uDC50|\\uD83D\\uDC51|\\uD83D\\uDC52|\\uD83D\\uDC53|\\uD83D\\uDC54|\\uD83D\\uDC55|\\uD83D\\uDC56|\\uD83D\\uDC57|\\uD83D\\uDC58|\\uD83D\\uDC59|\\uD83D\\uDC5A|\\uD83D\\uDC5B|\\uD83D\\uDC5C|\\uD83D\\uDC5D|\\uD83D\\uDC5E|\\uD83D\\uDC5F|\\uD83D\\uDC60|\\uD83D\\uDC61|\\uD83D\\uDC62|\\uD83D\\uDC63|\\uD83D\\uDC64|\\uD83D\\uDC66|\\uD83D\\uDC67|\\uD83D\\uDC68|\\uD83D\\uDC69|\\uD83D\\uDC6A|\\uD83D\\uDC6B|\\uD83D\\uDC6E|\\uD83D\\uDC6F|\\uD83D\\uDC70|\\uD83D\\uDC71|\\uD83D\\uDC72|\\uD83D\\uDC73|\\uD83D\\uDC74|\\uD83D\\uDC75|\\uD83D\\uDC76|\\uD83D\\uDC77|\\uD83D\\uDC78|\\uD83D\\uDC79|\\uD83D\\uDC7A|\\uD83D\\uDC7B|\\uD83D\\uDC7C|\\uD83D\\uDC7D|\\uD83D\\uDC7E|\\uD83D\\uDC7F|\\uD83D\\uDC80|\\uD83D\\uDCC7|\\uD83D\\uDC81|\\uD83D\\uDC82|\\uD83D\\uDC83|\\uD83D\\uDC84|\\uD83D\\uDC85|\\uD83D\\uDCD2|\\uD83D\\uDC86|\\uD83D\\uDCD3|\\uD83D\\uDC87|\\uD83D\\uDCD4|\\uD83D\\uDC88|\\uD83D\\uDCD5|\\uD83D\\uDC89|\\uD83D\\uDCD6|\\uD83D\\uDC8A|\\uD83D\\uDCD7|\\uD83D\\uDC8B|\\uD83D\\uDCD8|\\uD83D\\uDC8C|\\uD83D\\uDCD9|\\uD83D\\uDC8D|\\uD83D\\uDCDA|\\uD83D\\uDC8E|\\uD83D\\uDCDB|\\uD83D\\uDC8F|\\uD83D\\uDCDC|\\uD83D\\uDC90|\\uD83D\\uDCDD|\\uD83D\\uDC91|\\uD83D\\uDCDE|\\uD83D\\uDC92|\\uD83D\\uDCDF|\\uD83D\\uDCE0|\\uD83D\\uDC93|\\uD83D\\uDCE1|\\uD83D\\uDCE2|\\uD83D\\uDC94|\\uD83D\\uDCE3|\\uD83D\\uDCE4|\\uD83D\\uDC95|\\uD83D\\uDCE5|\\uD83D\\uDCE6|\\uD83D\\uDC96|\\uD83D\\uDCE7|\\uD83D\\uDCE8|\\uD83D\\uDC97|\\uD83D\\uDCE9|\\uD83D\\uDCEA|\\uD83D\\uDC98|\\uD83D\\uDCEB|\\uD83D\\uDCEE|\\uD83D\\uDC99|\\uD83D\\uDCF0|\\uD83D\\uDCF1|\\uD83D\\uDC9A|\\uD83D\\uDCF2|\\uD83D\\uDCF3|\\uD83D\\uDC9B|\\uD83D\\uDCF4|\\uD83D\\uDCF6|\\uD83D\\uDC9C|\\uD83D\\uDCF7|\\uD83D\\uDCF9|\\uD83D\\uDC9D|\\uD83D\\uDCFA|\\uD83D\\uDCFB|\\uD83D\\uDC9E|\\uD83D\\uDCFC|\\uD83D\\uDD03|\\uD83D\\uDC9F|\\uD83D\\uDD0A|\\uD83D\\uDD0B|\\uD83D\\uDCA0|\\uD83D\\uDD0C|\\uD83D\\uDD0D|\\uD83D\\uDCA1|\\uD83D\\uDD0E|\\uD83D\\uDD0F|\\uD83D\\uDCA2|\\uD83D\\uDD10|\\uD83D\\uDD11|\\uD83D\\uDCA3|\\uD83D\\uDD12|\\uD83D\\uDD13|\\uD83D\\uDCA4|\\uD83D\\uDD14|\\uD83D\\uDD16|\\uD83D\\uDCA5|\\uD83D\\uDD17|\\uD83D\\uDD18|\\uD83D\\uDCA6|\\uD83D\\uDD19|\\uD83D\\uDD1A|\\uD83D\\uDCA7|\\uD83D\\uDD1B|\\uD83D\\uDD1C|\\uD83D\\uDCA8|\\uD83D\\uDD1D|\\uD83D\\uDD1E|\\uD83D\\uDCA9|\\uD83D\\uDD1F|\\uD83D\\uDCAA|\\uD83D\\uDD20|\\uD83D\\uDD21|\\uD83D\\uDCAB|\\uD83D\\uDD22|\\uD83D\\uDD23|\\uD83D\\uDCAC|\\uD83D\\uDD24|\\uD83D\\uDD25|\\uD83D\\uDCAE|\\uD83D\\uDD26|\\uD83D\\uDD27|\\uD83D\\uDCAF|\\uD83D\\uDD28|\\uD83D\\uDD29|\\uD83D\\uDCB0|\\uD83D\\uDD2A|\\uD83D\\uDD2B|\\uD83D\\uDCB1|\\uD83D\\uDD2E|\\uD83D\\uDCB2|\\uD83D\\uDD2F|\\uD83D\\uDCB3|\\uD83D\\uDD30|\\uD83D\\uDD31|\\uD83D\\uDCB4|\\uD83D\\uDD32|\\uD83D\\uDD33|\\uD83D\\uDCB5|\\uD83D\\uDD34|\\uD83D\\uDD35|\\uD83D\\uDCB8|\\uD83D\\uDD36|\\uD83D\\uDD37|\\uD83D\\uDCB9|\\uD83D\\uDD38|\\uD83D\\uDD39|\\uD83D\\uDCBA|\\uD83D\\uDD3A|\\uD83D\\uDD3B|\\uD83D\\uDCBB|\\uD83D\\uDD3C|\\uD83D\\uDCBC|\\uD83D\\uDD3D|\\uD83D\\uDD50|\\uD83D\\uDCBD|\\uD83D\\uDD51|\\uD83D\\uDCBE|\\uD83D\\uDD52|\\uD83D\\uDCBF|\\uD83D\\uDD53|\\uD83D\\uDCC0|\\uD83D\\uDD54|\\uD83D\\uDD55|\\uD83D\\uDCC1|\\uD83D\\uDD56|\\uD83D\\uDD57|\\uD83D\\uDCC2|\\uD83D\\uDD58|\\uD83D\\uDD59|\\uD83D\\uDCC3|\\uD83D\\uDD5A|\\uD83D\\uDD5B|\\uD83D\\uDCC4|\\uD83D\\uDDFB|\\uD83D\\uDDFC|\\uD83D\\uDCC5|\\uD83D\\uDDFD|\\uD83D\\uDDFE|\\uD83D\\uDCC6|\\uD83D\\uDDFF|\\uD83D\\uDE01|\\uD83D\\uDE02|\\uD83D\\uDE03|\\uD83D\\uDCC8|\\uD83D\\uDE04|\\uD83D\\uDE05|\\uD83D\\uDCC9|\\uD83D\\uDE06|\\uD83D\\uDE09|\\uD83D\\uDCCA|\\uD83D\\uDE0A|\\uD83D\\uDE0B|\\uD83D\\uDCCB|\\uD83D\\uDE0C|\\uD83D\\uDE0D|\\uD83D\\uDCCC|\\uD83D\\uDE0F|\\uD83D\\uDE12|\\uD83D\\uDCCD|\\uD83D\\uDE13|\\uD83D\\uDE14|\\uD83D\\uDCCE|\\uD83D\\uDE16|\\uD83D\\uDE18|\\uD83D\\uDCCF|\\uD83D\\uDE1A|\\uD83D\\uDE1C|\\uD83D\\uDCD0|\\uD83D\\uDE1D|\\uD83D\\uDE1E|\\uD83D\\uDCD1|\\uD83D\\uDE20|\\uD83D\\uDE21|\\uD83D\\uDE22|\\uD83D\\uDE23|\\uD83D\\uDE24|\\uD83D\\uDE25|\\uD83D\\uDE28|\\uD83D\\uDE29|\\uD83D\\uDE2A|\\uD83D\\uDE2B|\\uD83D\\uDE2D|\\uD83D\\uDE30|\\uD83D\\uDE31|\\uD83D\\uDE32|\\uD83D\\uDE33|\\uD83D\\uDE35|\\uD83D\\uDE37|\\uD83D\\uDE38|\\uD83D\\uDE39|\\uD83D\\uDE3A|\\uD83D\\uDE3B|\\uD83D\\uDE3C|\\uD83D\\uDE3D|\\uD83D\\uDE3E|\\uD83D\\uDE3F|\\uD83D\\uDE40|\\uD83D\\uDE45|\\uD83D\\uDE46|\\uD83D\\uDE47|\\uD83D\\uDE48|\\uD83D\\uDE49|\\uD83D\\uDE4A|\\uD83D\\uDE4B|\\uD83D\\uDE4C|\\uD83D\\uDE4D|\\uD83D\\uDE4E|\\uD83D\\uDE4F|\\uD83D\\uDE80|\\uD83D\\uDE83|\\uD83D\\uDE84|\\uD83D\\uDE85|\\uD83D\\uDE87|\\uD83D\\uDE89|\\uD83D\\uDE8C|\\uD83D\\uDE8F|\\uD83D\\uDE91|\\uD83D\\uDE92|\\uD83D\\uDE93|\\uD83D\\uDE95|\\uD83D\\uDE97|\\uD83D\\uDE99|\\uD83D\\uDE9A|\\uD83D\\uDEA2|\\uD83D\\uDEA4|\\uD83D\\uDEA5|\\uD83D\\uDEA7|\\uD83D\\uDEA8|\\uD83D\\uDEA9|\\uD83D\\uDEAA|\\uD83D\\uDEAB|\\uD83D\\uDEAC|\\uD83D\\uDEAD|\\uD83D\\uDEB2|\\uD83D\\uDEB6|\\uD83D\\uDEB9|\\uD83D\\uDEBA|\\uD83D\\uDEBB|\\uD83D\\uDEBC|\\uD83D\\uDEBD|\\uD83D\\uDEBE|\\uD83D\\uDEC0|\\uD83D\\uDE00|\\uD83D\\uDE07|\\uD83D\\uDE08|\\uD83D\\uDE0E|\\uD83D\\uDE10|\\uD83D\\uDE11|\\uD83D\\uDE15|\\uD83D\\uDE17|\\uD83D\\uDE19|\\uD83D\\uDE1B|\\uD83D\\uDE1F|\\uD83D\\uDE26|\\uD83D\\uDE27|\\uD83D\\uDE2C|\\uD83D\\uDE2E|\\uD83D\\uDE2F|\\uD83D\\uDE34|\\uD83D\\uDE36|\\uD83D\\uDE81|\\uD83D\\uDE82|\\uD83D\\uDE86|\\uD83D\\uDE88|\\uD83D\\uDE8A|\\uD83D\\uDE8D|\\uD83D\\uDE8E|\\uD83D\\uDE90|\\uD83D\\uDE94|\\uD83D\\uDE96|\\uD83D\\uDE98|\\uD83D\\uDE9B|\\uD83D\\uDE9C|\\uD83D\\uDE9D|\\uD83D\\uDE9E|\\uD83D\\uDE9F|\\uD83D\\uDEA0|\\uD83D\\uDEA1|\\uD83D\\uDEA3|\\uD83D\\uDEA6|\\uD83D\\uDEAE|\\uD83D\\uDEAF|\\uD83D\\uDEB0|\\uD83D\\uDEB1|\\uD83D\\uDEB3|\\uD83D\\uDEB4|\\uD83D\\uDEB5|\\uD83D\\uDEB7|\\uD83D\\uDEB8|\\uD83D\\uDEBF|\\uD83D\\uDEC1|\\uD83D\\uDEC2|\\uD83D\\uDEC3|\\uD83D\\uDEC4|\\uD83D\\uDEC5|\\uD83C\\uDF0D|\\uD83C\\uDF0E|\\uD83C\\uDF10|\\uD83C\\uDF12|\\uD83C\\uDF16|\\uD83C\\uDF17|\\uD83C\\uDF18|\\uD83C\\uDF1A|\\uD83C\\uDF1C|\\uD83C\\uDF1D|\\uD83C\\uDF1E|\\uD83C\\uDF32|\\uD83C\\uDF33|\\uD83C\\uDF4B|\\uD83C\\uDF50|\\uD83C\\uDF7C|\\uD83C\\uDFC7|\\uD83C\\uDFC9|\\uD83C\\uDFE4|\\uD83D\\uDC00|\\uD83D\\uDC01|\\uD83D\\uDC02|\\uD83D\\uDC03|\\uD83D\\uDC04|\\uD83D\\uDC05|\\uD83D\\uDC06|\\uD83D\\uDC07|\\uD83D\\uDC08|\\uD83D\\uDC09|\\uD83D\\uDC0A|\\uD83D\\uDC0B|\\uD83D\\uDC0F|\\uD83D\\uDC10|\\uD83D\\uDC13|\\uD83D\\uDC15|\\uD83D\\uDC16|\\uD83D\\uDC2A|\\uD83D\\uDC65|\\uD83D\\uDC6C|\\uD83D\\uDC6D|\\uD83D\\uDCAD|\\uD83D\\uDCB6|\\uD83D\\uDCB7|\\uD83D\\uDCEC|\\uD83D\\uDCED|\\uD83D\\uDCEF|\\uD83D\\uDCF5|\\uD83D\\uDD00|\\uD83D\\uDD01|\\uD83D\\uDD02|\\uD83D\\uDD04|\\uD83D\\uDD05|\\uD83D\\uDD06|\\uD83D\\uDD07|\\uD83D\\uDD09|\\uD83D\\uDD15|\\uD83D\\uDD2C|\\uD83D\\uDD2D|\\uD83D\\uDD5C|\\uD83D\\uDD5D|\\uD83D\\uDD5E|\\uD83D\\uDD5F|\\uD83D\\uDD60|\\uD83D\\uDD61|\\uD83D\\uDD62|\\uD83D\\uDD63|\\uD83D\\uDD64|\\uD83D\\uDD65|\\uD83D\\uDD66|\\uD83D\\uDD67|\\uD83D\\uDD08|\\uD83D\\uDE8B|\\u27BF|\\uD83C\\uDDE6\\uD83C\\uDDEB|\\uD83C\\uDDE6\\uD83C\\uDDF1|\\uD83C\\uDDE9\\uD83C\\uDDFF|\\uD83C\\uDDE6\\uD83C\\uDDE9|\\uD83C\\uDDE6\\uD83C\\uDDF4|\\uD83C\\uDDE6\\uD83C\\uDDEC|\\uD83C\\uDDE6\\uD83C\\uDDF7|\\uD83C\\uDDE6\\uD83C\\uDDF2|\\uD83C\\uDDE6\\uD83C\\uDDFA|\\uD83C\\uDDE6\\uD83C\\uDDF9|\\uD83C\\uDDE6\\uD83C\\uDDFF|\\uD83C\\uDDE7\\uD83C\\uDDF8|\\uD83C\\uDDE7\\uD83C\\uDDED|\\uD83C\\uDDE7\\uD83C\\uDDE9|\\uD83C\\uDDE7\\uD83C\\uDDE7|\\uD83C\\uDDE7\\uD83C\\uDDFE|\\uD83C\\uDDE7\\uD83C\\uDDEA|\\uD83C\\uDDE7\\uD83C\\uDDFF|\\uD83C\\uDDE7\\uD83C\\uDDEF|\\uD83C\\uDDE7\\uD83C\\uDDF9|\\uD83C\\uDDE7\\uD83C\\uDDF4|\\uD83C\\uDDE7\\uD83C\\uDDE6|\\uD83C\\uDDE7\\uD83C\\uDDFC|\\uD83C\\uDDE7\\uD83C\\uDDF7|\\uD83C\\uDDE7\\uD83C\\uDDF3|\\uD83C\\uDDE7\\uD83C\\uDDEC|\\uD83C\\uDDE7\\uD83C\\uDDEB|\\uD83C\\uDDE7\\uD83C\\uDDEE|\\uD83C\\uDDF0\\uD83C\\uDDED|\\uD83C\\uDDE8\\uD83C\\uDDF2|\\uD83C\\uDDE8\\uD83C\\uDDE6|\\uD83C\\uDDE8\\uD83C\\uDDFB|\\uD83C\\uDDE8\\uD83C\\uDDEB|\\uD83C\\uDDF9\\uD83C\\uDDE9|\\uD83C\\uDDE8\\uD83C\\uDDF1|\\uD83C\\uDDE8\\uD83C\\uDDF4|\\uD83C\\uDDF0\\uD83C\\uDDF2|\\uD83C\\uDDE8\\uD83C\\uDDF7|\\uD83C\\uDDE8\\uD83C\\uDDEE|\\uD83C\\uDDED\\uD83C\\uDDF7|\\uD83C\\uDDE8\\uD83C\\uDDFA|\\uD83C\\uDDE8\\uD83C\\uDDFE|\\uD83C\\uDDE8\\uD83C\\uDDFF|\\uD83C\\uDDE8\\uD83C\\uDDE9|\\uD83C\\uDDE9\\uD83C\\uDDF0|\\uD83C\\uDDE9\\uD83C\\uDDEF|\\uD83C\\uDDE9\\uD83C\\uDDF2|\\uD83C\\uDDE9\\uD83C\\uDDF4|\\uD83C\\uDDF9\\uD83C\\uDDF1|\\uD83C\\uDDEA\\uD83C\\uDDE8|\\uD83C\\uDDEA\\uD83C\\uDDEC|\\uD83C\\uDDF8\\uD83C\\uDDFB|\\uD83C\\uDDEC\\uD83C\\uDDF6|\\uD83C\\uDDEA\\uD83C\\uDDF7|\\uD83C\\uDDEA\\uD83C\\uDDEA|\\uD83C\\uDDEA\\uD83C\\uDDF9|\\uD83C\\uDDEB\\uD83C\\uDDEF|\\uD83C\\uDDEB\\uD83C\\uDDEE|\\uD83C\\uDDEC\\uD83C\\uDDE6|\\uD83C\\uDDEC\\uD83C\\uDDF2|\\uD83C\\uDDEC\\uD83C\\uDDEA|\\uD83C\\uDDEC\\uD83C\\uDDED|\\uD83C\\uDDEC\\uD83C\\uDDF7|\\uD83C\\uDDEC\\uD83C\\uDDE9|\\uD83C\\uDDEC\\uD83C\\uDDF9|\\uD83C\\uDDEC\\uD83C\\uDDF3|\\uD83C\\uDDEC\\uD83C\\uDDFC|\\uD83C\\uDDEC\\uD83C\\uDDFE|\\uD83C\\uDDED\\uD83C\\uDDF9|\\uD83C\\uDDED\\uD83C\\uDDF3|\\uD83C\\uDDED\\uD83C\\uDDFA|\\uD83C\\uDDEE\\uD83C\\uDDF8|\\uD83C\\uDDEE\\uD83C\\uDDF3|\\uD83C\\uDDEE\\uD83C\\uDDE9|\\uD83C\\uDDEE\\uD83C\\uDDF7|\\uD83C\\uDDEE\\uD83C\\uDDF6|\\uD83C\\uDDEE\\uD83C\\uDDEA|\\uD83C\\uDDEE\\uD83C\\uDDF1|\\uD83C\\uDDEF\\uD83C\\uDDF2|\\uD83C\\uDDEF\\uD83C\\uDDF4|\\uD83C\\uDDF0\\uD83C\\uDDFF|\\uD83C\\uDDF0\\uD83C\\uDDEA|\\uD83C\\uDDF0\\uD83C\\uDDEE|\\uD83C\\uDDFD\\uD83C\\uDDF0|\\uD83C\\uDDF0\\uD83C\\uDDFC|\\uD83C\\uDDF0\\uD83C\\uDDEC|\\uD83C\\uDDF1\\uD83C\\uDDE6|\\uD83C\\uDDF1\\uD83C\\uDDFB|\\uD83C\\uDDF1\\uD83C\\uDDE7|\\uD83C\\uDDF1\\uD83C\\uDDF8|\\uD83C\\uDDF1\\uD83C\\uDDF7|\\uD83C\\uDDF1\\uD83C\\uDDFE|\\uD83C\\uDDF1\\uD83C\\uDDEE|\\uD83C\\uDDF1\\uD83C\\uDDF9|\\uD83C\\uDDF1\\uD83C\\uDDFA|\\uD83C\\uDDF2\\uD83C\\uDDF0|\\uD83C\\uDDF2\\uD83C\\uDDEC|\\uD83C\\uDDF2\\uD83C\\uDDFC|\\uD83C\\uDDF2\\uD83C\\uDDFE|\\uD83C\\uDDF2\\uD83C\\uDDFB|\\uD83C\\uDDF2\\uD83C\\uDDF1|\\uD83C\\uDDF2\\uD83C\\uDDF9|\\uD83C\\uDDF2\\uD83C\\uDDED|\\uD83C\\uDDF2\\uD83C\\uDDF7|\\uD83C\\uDDF2\\uD83C\\uDDFA|\\uD83C\\uDDF2\\uD83C\\uDDFD|\\uD83C\\uDDEB\\uD83C\\uDDF2|\\uD83C\\uDDF2\\uD83C\\uDDE9|\\uD83C\\uDDF2\\uD83C\\uDDE8|\\uD83C\\uDDF2\\uD83C\\uDDF3|\\uD83C\\uDDF2\\uD83C\\uDDEA|\\uD83C\\uDDF2\\uD83C\\uDDE6|\\uD83C\\uDDF2\\uD83C\\uDDFF|\\uD83C\\uDDF2\\uD83C\\uDDF2|\\uD83C\\uDDF3\\uD83C\\uDDE6|\\uD83C\\uDDF3\\uD83C\\uDDF7|\\uD83C\\uDDF3\\uD83C\\uDDF5|\\uD83C\\uDDF3\\uD83C\\uDDF1|\\uD83C\\uDDF3\\uD83C\\uDDFF|\\uD83C\\uDDF3\\uD83C\\uDDEE|\\uD83C\\uDDF3\\uD83C\\uDDEA|\\uD83C\\uDDF3\\uD83C\\uDDEC|\\uD83C\\uDDF0\\uD83C\\uDDF5|\\uD83C\\uDDF3\\uD83C\\uDDF4|\\uD83C\\uDDF4\\uD83C\\uDDF2|\\uD83C\\uDDF5\\uD83C\\uDDF0|\\uD83C\\uDDF5\\uD83C\\uDDFC|\\uD83C\\uDDF5\\uD83C\\uDDE6|\\uD83C\\uDDF5\\uD83C\\uDDEC|\\uD83C\\uDDF5\\uD83C\\uDDFE|\\uD83C\\uDDF5\\uD83C\\uDDEA|\\uD83C\\uDDF5\\uD83C\\uDDED|\\uD83C\\uDDF5\\uD83C\\uDDF1|\\uD83C\\uDDF5\\uD83C\\uDDF9|\\uD83C\\uDDF6\\uD83C\\uDDE6|\\uD83C\\uDDF9\\uD83C\\uDDFC|\\uD83C\\uDDE8\\uD83C\\uDDEC|\\uD83C\\uDDF7\\uD83C\\uDDF4|\\uD83C\\uDDF7\\uD83C\\uDDFC|\\uD83C\\uDDF0\\uD83C\\uDDF3|\\uD83C\\uDDF1\\uD83C\\uDDE8|\\uD83C\\uDDFB\\uD83C\\uDDE8|\\uD83C\\uDDFC\\uD83C\\uDDF8|\\uD83C\\uDDF8\\uD83C\\uDDF2|\\uD83C\\uDDF8\\uD83C\\uDDF9|\\uD83C\\uDDF8\\uD83C\\uDDE6|\\uD83C\\uDDF8\\uD83C\\uDDF3|\\uD83C\\uDDF7\\uD83C\\uDDF8|\\uD83C\\uDDF8\\uD83C\\uDDE8|\\uD83C\\uDDF8\\uD83C\\uDDF1|\\uD83C\\uDDF8\\uD83C\\uDDEC|\\uD83C\\uDDF8\\uD83C\\uDDF0|\\uD83C\\uDDF8\\uD83C\\uDDEE|\\uD83C\\uDDF8\\uD83C\\uDDE7|\\uD83C\\uDDF8\\uD83C\\uDDF4|\\uD83C\\uDDFF\\uD83C\\uDDE6|\\uD83C\\uDDF1\\uD83C\\uDDF0|\\uD83C\\uDDF8\\uD83C\\uDDE9|\\uD83C\\uDDF8\\uD83C\\uDDF7|\\uD83C\\uDDF8\\uD83C\\uDDFF|\\uD83C\\uDDF8\\uD83C\\uDDEA|\\uD83C\\uDDE8\\uD83C\\uDDED|\\uD83C\\uDDF8\\uD83C\\uDDFE|\\uD83C\\uDDF9\\uD83C\\uDDEF|\\uD83C\\uDDF9\\uD83C\\uDDFF|\\uD83C\\uDDF9\\uD83C\\uDDED|\\uD83C\\uDDF9\\uD83C\\uDDEC|\\uD83C\\uDDF9\\uD83C\\uDDF4|\\uD83C\\uDDF9\\uD83C\\uDDF9|\\uD83C\\uDDF9\\uD83C\\uDDF3|\\uD83C\\uDDF9\\uD83C\\uDDF7|\\uD83C\\uDDF9\\uD83C\\uDDF2|\\uD83C\\uDDF9\\uD83C\\uDDFB|\\uD83C\\uDDFA\\uD83C\\uDDEC|\\uD83C\\uDDFA\\uD83C\\uDDE6|\\uD83C\\uDDE6\\uD83C\\uDDEA|\\uD83C\\uDDFA\\uD83C\\uDDFE|\\uD83C\\uDDFA\\uD83C\\uDDFF|\\uD83C\\uDDFB\\uD83C\\uDDFA|\\uD83C\\uDDFB\\uD83C\\uDDE6|\\uD83C\\uDDFB\\uD83C\\uDDEA|\\uD83C\\uDDFB\\uD83C\\uDDF3|\\uD83C\\uDDEA\\uD83C\\uDDED|\\uD83C\\uDDFE\\uD83C\\uDDEA|\\uD83C\\uDDFF\\uD83C\\uDDF2|\\uD83C\\uDDFF\\uD83C\\uDDFC|\\uD83C\\uDDF5\\uD83C\\uDDF7|\\uD83C\\uDDF0\\uD83C\\uDDFE|\\uD83C\\uDDE7\\uD83C\\uDDF2|\\uD83C\\uDDF5\\uD83C\\uDDEB|\\uD83C\\uDDF5\\uD83C\\uDDF8|\\uD83C\\uDDF3\\uD83C\\uDDE8|\\uD83C\\uDDF8\\uD83C\\uDDED|\\uD83C\\uDDE6\\uD83C\\uDDFC|\\uD83C\\uDDFB\\uD83C\\uDDEE|\\uD83C\\uDDED\\uD83C\\uDDF0|\\uD83C\\uDDE6\\uD83C\\uDDE8|\\uD83C\\uDDF2\\uD83C\\uDDF8|\\uD83C\\uDDEC\\uD83C\\uDDFA|\\uD83C\\uDDEC\\uD83C\\uDDF1|\\uD83C\\uDDF3\\uD83C\\uDDFA|\\uD83C\\uDDFC\\uD83C\\uDDEB|\\uD83C\\uDDF2\\uD83C\\uDDF4|\\uD83C\\uDDEB\\uD83C\\uDDF4|\\uD83C\\uDDEB\\uD83C\\uDDF0|\\uD83C\\uDDEF\\uD83C\\uDDEA|\\uD83C\\uDDE6\\uD83C\\uDDEE|\\uD83C\\uDDEC\\uD83C\\uDDEE)",
a.jsecapeMap={"#️⃣":"0023-20E3","#⃣":"0023-20E3","0️⃣":"0030-20E3","0⃣":"0030-20E3","1️⃣":"0031-20E3","1⃣":"0031-20E3","2️⃣":"0032-20E3","2⃣":"0032-20E3","3️⃣":"0033-20E3","3⃣":"0033-20E3","4️⃣":"0034-20E3","4⃣":"0034-20E3","5️⃣":"0035-20E3","5⃣":"0035-20E3","6️⃣":"0036-20E3","6⃣":"0036-20E3","7️⃣":"0037-20E3","7⃣":"0037-20E3","8️⃣":"0038-20E3","8⃣":"0038-20E3","9️⃣":"0039-20E3","9⃣":"0039-20E3","©":"00A9","®":"00AE","‼️":"203C","‼":"203C","⁉️":"2049","⁉":"2049","™":"2122","ℹ️":"2139","ℹ":"2139","↔️":"2194","↔":"2194","↕️":"2195","↕":"2195","↖️":"2196","↖":"2196","↗️":"2197","↗":"2197","↘️":"2198","↘":"2198","↙️":"2199","↙":"2199","↩️":"21A9","↩":"21A9","↪️":"21AA","↪":"21AA","⌚️":"231A","⌚":"231A","⌛️":"231B","⌛":"231B","⏩":"23E9","⏪":"23EA","⏫":"23EB","⏬":"23EC","⏰":"23F0","⏳":"23F3","Ⓜ️":"24C2","Ⓜ":"24C2","▪️":"25AA","▪":"25AA","▫️":"25AB","▫":"25AB","▶️":"25B6","▶":"25B6","◀️":"25C0","◀":"25C0","◻️":"25FB","◻":"25FB","◼️":"25FC","◼":"25FC","◽️":"25FD","◽":"25FD","◾️":"25FE","◾":"25FE","☀️":"2600","☀":"2600","☁️":"2601","☁":"2601","☎️":"260E","☎":"260E","☑️":"2611","☑":"2611","☔️":"2614","☔":"2614","☕️":"2615","☕":"2615","☝️":"261D","☝":"261D","☺️":"263A","☺":"263A","♈️":"2648","♈":"2648","♉️":"2649","♉":"2649","♊️":"264A","♊":"264A","♋️":"264B","♋":"264B","♌️":"264C","♌":"264C","♍️":"264D","♍":"264D","♎️":"264E","♎":"264E","♏️":"264F","♏":"264F","♐️":"2650","♐":"2650","♑️":"2651","♑":"2651","♒️":"2652","♒":"2652","♓️":"2653","♓":"2653","♠️":"2660","♠":"2660","♣️":"2663","♣":"2663","♥️":"2665","♥":"2665","♦️":"2666","♦":"2666","♨️":"2668","♨":"2668","♻️":"267B","♻":"267B","♿️":"267F","♿":"267F","⚓️":"2693","⚓":"2693","⚠️":"26A0","⚠":"26A0","⚡️":"26A1","⚡":"26A1","⚪️":"26AA","⚪":"26AA","⚫️":"26AB","⚫":"26AB","⚽️":"26BD","⚽":"26BD","⚾️":"26BE","⚾":"26BE","⛄️":"26C4","⛄":"26C4","⛅️":"26C5","⛅":"26C5","⛎":"26CE","⛔️":"26D4","⛔":"26D4","⛪️":"26EA","⛪":"26EA","⛲️":"26F2","⛲":"26F2","⛳️":"26F3","⛳":"26F3","⛵️":"26F5","⛵":"26F5","⛺️":"26FA","⛺":"26FA","⛽️":"26FD","⛽":"26FD","✂️":"2702","✂":"2702","✅":"2705","✈️":"2708","✈":"2708","✉️":"2709","✉":"2709","✊":"270A","✋":"270B","✌️":"270C","✌":"270C","✏️":"270F","✏":"270F","✒️":"2712","✒":"2712","✔️":"2714","✔":"2714","✖️":"2716","✖":"2716","✨":"2728","✳️":"2733","✳":"2733","✴️":"2734","✴":"2734","❄️":"2744","❄":"2744","❇️":"2747","❇":"2747","❌":"274C","❎":"274E","❓":"2753","❔":"2754","❕":"2755","❗️":"2757","❗":"2757","❤️":"2764","❤":"2764","➕":"2795","➖":"2796","➗":"2797","➡️":"27A1","➡":"27A1","➰":"27B0","⤴️":"2934","⤴":"2934","⤵️":"2935","⤵":"2935","⬅️":"2B05","⬅":"2B05","⬆️":"2B06","⬆":"2B06","⬇️":"2B07","⬇":"2B07","⬛️":"2B1B","⬛":"2B1B","⬜️":"2B1C","⬜":"2B1C","⭐️":"2B50","⭐":"2B50","⭕️":"2B55","⭕":"2B55","〰":"3030","〽️":"303D","〽":"303D","㊗️":"3297","㊗":"3297","㊙️":"3299","㊙":"3299","🀄️":"1F004","🀄":"1F004","🃏":"1F0CF","🅰":"1F170","🅱":"1F171","🅾":"1F17E","🅿️":"1F17F","🅿":"1F17F","🆎":"1F18E","🆑":"1F191","🆒":"1F192","🆓":"1F193","🆔":"1F194","🆕":"1F195","🆖":"1F196","🆗":"1F197","🆘":"1F198","🆙":"1F199","🆚":"1F19A","🇨🇳":"1F1E8-1F1F3","🇩🇪":"1F1E9-1F1EA","🇪🇸":"1F1EA-1F1F8","🇫🇷":"1F1EB-1F1F7","🇬🇧":"1F1EC-1F1E7","🇮🇹":"1F1EE-1F1F9","🇯🇵":"1F1EF-1F1F5","🇰🇷":"1F1F0-1F1F7","🇺🇸":"1F1FA-1F1F8","🇷🇺":"1F1F7-1F1FA","🈁":"1F201","🈂":"1F202","🈚️":"1F21A","🈚":"1F21A","🈯️":"1F22F","🈯":"1F22F","🈲":"1F232","🈳":"1F233","🈴":"1F234","🈵":"1F235","🈶":"1F236","🈷":"1F237","🈸":"1F238","🈹":"1F239","🈺":"1F23A","🉐":"1F250","🉑":"1F251","🌀":"1F300","🌁":"1F301","🌂":"1F302","🌃":"1F303","🌄":"1F304","🌅":"1F305","🌆":"1F306","🌇":"1F307","🌈":"1F308","🌉":"1F309","🌊":"1F30A","🌋":"1F30B","🌌":"1F30C","🌏":"1F30F","🌑":"1F311","🌓":"1F313","🌔":"1F314","🌕":"1F315","🌙":"1F319","🌛":"1F31B","🌟":"1F31F","🌠":"1F320","🌰":"1F330","🌱":"1F331","🌴":"1F334","🌵":"1F335","🌷":"1F337","🌸":"1F338","🌹":"1F339","🌺":"1F33A","🌻":"1F33B","🌼":"1F33C","🌽":"1F33D","🌾":"1F33E","🌿":"1F33F","🍀":"1F340","🍁":"1F341","🍂":"1F342","🍃":"1F343","🍄":"1F344","🍅":"1F345","🍆":"1F346","🍇":"1F347","🍈":"1F348","🍉":"1F349","🍊":"1F34A","🍌":"1F34C","🍍":"1F34D","🍎":"1F34E","🍏":"1F34F","🍑":"1F351","🍒":"1F352","🍓":"1F353","🍔":"1F354","🍕":"1F355","🍖":"1F356","🍗":"1F357","🍘":"1F358","🍙":"1F359","🍚":"1F35A","🍛":"1F35B","🍜":"1F35C","🍝":"1F35D","🍞":"1F35E","🍟":"1F35F","🍠":"1F360","🍡":"1F361","🍢":"1F362","🍣":"1F363","🍤":"1F364","🍥":"1F365","🍦":"1F366","🍧":"1F367","🍨":"1F368","🍩":"1F369","🍪":"1F36A","🍫":"1F36B","🍬":"1F36C","🍭":"1F36D","🍮":"1F36E","🍯":"1F36F","🍰":"1F370","🍱":"1F371","🍲":"1F372","🍳":"1F373","🍴":"1F374","🍵":"1F375","🍶":"1F376","🍷":"1F377","🍸":"1F378","🍹":"1F379","🍺":"1F37A","🍻":"1F37B","🎀":"1F380","🎁":"1F381","🎂":"1F382","🎃":"1F383","🎄":"1F384","🎅":"1F385","🎆":"1F386","🎇":"1F387","🎈":"1F388","🎉":"1F389","🎊":"1F38A","🎋":"1F38B","🎌":"1F38C","🎍":"1F38D","🎎":"1F38E","🎏":"1F38F","🎐":"1F390","🎑":"1F391","🎒":"1F392","🎓":"1F393","🎠":"1F3A0","🎡":"1F3A1","🎢":"1F3A2","🎣":"1F3A3","🎤":"1F3A4","🎥":"1F3A5","🎦":"1F3A6","🎧":"1F3A7","🎨":"1F3A8","🎩":"1F3A9","🎪":"1F3AA","🎫":"1F3AB","🎬":"1F3AC","🎭":"1F3AD","🎮":"1F3AE","🎯":"1F3AF","🎰":"1F3B0","🎱":"1F3B1","🎲":"1F3B2","🎳":"1F3B3","🎴":"1F3B4","🎵":"1F3B5","🎶":"1F3B6","🎷":"1F3B7","🎸":"1F3B8","🎹":"1F3B9","🎺":"1F3BA","🎻":"1F3BB","🎼":"1F3BC","🎽":"1F3BD","🎾":"1F3BE","🎿":"1F3BF","🏀":"1F3C0","🏁":"1F3C1","🏂":"1F3C2","🏃":"1F3C3","🏄":"1F3C4","🏆":"1F3C6","🏈":"1F3C8","🏊":"1F3CA","🏠":"1F3E0","🏡":"1F3E1","🏢":"1F3E2","🏣":"1F3E3","🏥":"1F3E5","🏦":"1F3E6","🏧":"1F3E7","🏨":"1F3E8","🏩":"1F3E9","🏪":"1F3EA","🏫":"1F3EB","🏬":"1F3EC","🏭":"1F3ED","🏮":"1F3EE","🏯":"1F3EF","🏰":"1F3F0","🐌":"1F40C","🐍":"1F40D","🐎":"1F40E","🐑":"1F411","🐒":"1F412","🐔":"1F414","🐗":"1F417","🐘":"1F418","🐙":"1F419","🐚":"1F41A","🐛":"1F41B","🐜":"1F41C","🐝":"1F41D","🐞":"1F41E","🐟":"1F41F","🐠":"1F420","🐡":"1F421","🐢":"1F422","🐣":"1F423","🐤":"1F424","🐥":"1F425","🐦":"1F426","🐧":"1F427","🐨":"1F428","🐩":"1F429","🐫":"1F42B","🐬":"1F42C","🐭":"1F42D","🐮":"1F42E","🐯":"1F42F","🐰":"1F430","🐱":"1F431","🐲":"1F432","🐳":"1F433","🐴":"1F434","🐵":"1F435","🐶":"1F436","🐷":"1F437","🐸":"1F438","🐹":"1F439","🐺":"1F43A","🐻":"1F43B","🐼":"1F43C","🐽":"1F43D","🐾":"1F43E","👀":"1F440","👂":"1F442","👃":"1F443","👄":"1F444","👅":"1F445","👆":"1F446","👇":"1F447","👈":"1F448","👉":"1F449","👊":"1F44A","👋":"1F44B","👌":"1F44C","👍":"1F44D","👎":"1F44E","👏":"1F44F","👐":"1F450","👑":"1F451","👒":"1F452","👓":"1F453","👔":"1F454","👕":"1F455","👖":"1F456","👗":"1F457","👘":"1F458","👙":"1F459","👚":"1F45A","👛":"1F45B","👜":"1F45C","👝":"1F45D","👞":"1F45E","👟":"1F45F","👠":"1F460","👡":"1F461","👢":"1F462","👣":"1F463","👤":"1F464","👦":"1F466","👧":"1F467","👨":"1F468","👩":"1F469","👪":"1F46A","👫":"1F46B","👮":"1F46E","👯":"1F46F","👰":"1F470","👱":"1F471","👲":"1F472","👳":"1F473","👴":"1F474","👵":"1F475","👶":"1F476","👷":"1F477","👸":"1F478","👹":"1F479","👺":"1F47A","👻":"1F47B","👼":"1F47C","👽":"1F47D","👾":"1F47E","👿":"1F47F","💀":"1F480","📇":"1F4C7","💁":"1F481","💂":"1F482","💃":"1F483","💄":"1F484","💅":"1F485","📒":"1F4D2","💆":"1F486","📓":"1F4D3","💇":"1F487","📔":"1F4D4","💈":"1F488","📕":"1F4D5","💉":"1F489","📖":"1F4D6","💊":"1F48A","📗":"1F4D7","💋":"1F48B","📘":"1F4D8","💌":"1F48C","📙":"1F4D9","💍":"1F48D","📚":"1F4DA","💎":"1F48E","📛":"1F4DB","💏":"1F48F","📜":"1F4DC","💐":"1F490","📝":"1F4DD","💑":"1F491","📞":"1F4DE","💒":"1F492","📟":"1F4DF","📠":"1F4E0","💓":"1F493","📡":"1F4E1","📢":"1F4E2","💔":"1F494","📣":"1F4E3","📤":"1F4E4","💕":"1F495","📥":"1F4E5","📦":"1F4E6","💖":"1F496","📧":"1F4E7","📨":"1F4E8","💗":"1F497","📩":"1F4E9","📪":"1F4EA","💘":"1F498","📫":"1F4EB","📮":"1F4EE","💙":"1F499","📰":"1F4F0","📱":"1F4F1","💚":"1F49A","📲":"1F4F2","📳":"1F4F3","💛":"1F49B","📴":"1F4F4","📶":"1F4F6","💜":"1F49C","📷":"1F4F7","📹":"1F4F9","💝":"1F49D","📺":"1F4FA","📻":"1F4FB","💞":"1F49E","📼":"1F4FC","🔃":"1F503","💟":"1F49F","🔊":"1F50A","🔋":"1F50B","💠":"1F4A0","🔌":"1F50C","🔍":"1F50D","💡":"1F4A1","🔎":"1F50E","🔏":"1F50F","💢":"1F4A2","🔐":"1F510","🔑":"1F511","💣":"1F4A3","🔒":"1F512","🔓":"1F513","💤":"1F4A4","🔔":"1F514","🔖":"1F516","💥":"1F4A5","🔗":"1F517","🔘":"1F518","💦":"1F4A6","🔙":"1F519","🔚":"1F51A","💧":"1F4A7","🔛":"1F51B","🔜":"1F51C","💨":"1F4A8","🔝":"1F51D","🔞":"1F51E","💩":"1F4A9","🔟":"1F51F","💪":"1F4AA","🔠":"1F520","🔡":"1F521","💫":"1F4AB","🔢":"1F522","🔣":"1F523","💬":"1F4AC","🔤":"1F524","🔥":"1F525","💮":"1F4AE","🔦":"1F526","🔧":"1F527","💯":"1F4AF","🔨":"1F528","🔩":"1F529","💰":"1F4B0","🔪":"1F52A","🔫":"1F52B","💱":"1F4B1","🔮":"1F52E","💲":"1F4B2","🔯":"1F52F","💳":"1F4B3","🔰":"1F530","🔱":"1F531","💴":"1F4B4","🔲":"1F532","🔳":"1F533","💵":"1F4B5","🔴":"1F534","🔵":"1F535","💸":"1F4B8","🔶":"1F536","🔷":"1F537","💹":"1F4B9","🔸":"1F538","🔹":"1F539","💺":"1F4BA","🔺":"1F53A","🔻":"1F53B","💻":"1F4BB","🔼":"1F53C","💼":"1F4BC","🔽":"1F53D","🕐":"1F550","💽":"1F4BD","🕑":"1F551","💾":"1F4BE","🕒":"1F552","💿":"1F4BF","🕓":"1F553","📀":"1F4C0","🕔":"1F554","🕕":"1F555","📁":"1F4C1","🕖":"1F556","🕗":"1F557","📂":"1F4C2","🕘":"1F558","🕙":"1F559","📃":"1F4C3","🕚":"1F55A","🕛":"1F55B","📄":"1F4C4","🗻":"1F5FB","🗼":"1F5FC","📅":"1F4C5","🗽":"1F5FD","🗾":"1F5FE","📆":"1F4C6","🗿":"1F5FF","😁":"1F601","😂":"1F602","😃":"1F603","📈":"1F4C8","😄":"1F604","😅":"1F605","📉":"1F4C9","😆":"1F606","😉":"1F609","📊":"1F4CA","😊":"1F60A","😋":"1F60B","📋":"1F4CB","😌":"1F60C","😍":"1F60D","📌":"1F4CC","😏":"1F60F","😒":"1F612","📍":"1F4CD","😓":"1F613","😔":"1F614","📎":"1F4CE","😖":"1F616","😘":"1F618","📏":"1F4CF","😚":"1F61A","😜":"1F61C","📐":"1F4D0","😝":"1F61D","😞":"1F61E","📑":"1F4D1","😠":"1F620","😡":"1F621","😢":"1F622","😣":"1F623","😤":"1F624","😥":"1F625","😨":"1F628","😩":"1F629","😪":"1F62A","😫":"1F62B","😭":"1F62D","😰":"1F630","😱":"1F631","😲":"1F632","😳":"1F633","😵":"1F635","😷":"1F637","😸":"1F638","😹":"1F639","😺":"1F63A","😻":"1F63B","😼":"1F63C","😽":"1F63D","😾":"1F63E","😿":"1F63F","🙀":"1F640","🙅":"1F645","🙆":"1F646","🙇":"1F647","🙈":"1F648","🙉":"1F649","🙊":"1F64A","🙋":"1F64B","🙌":"1F64C","🙍":"1F64D","🙎":"1F64E","🙏":"1F64F","🚀":"1F680","🚃":"1F683","🚄":"1F684","🚅":"1F685","🚇":"1F687","🚉":"1F689","🚌":"1F68C","🚏":"1F68F","🚑":"1F691","🚒":"1F692","🚓":"1F693","🚕":"1F695","🚗":"1F697","🚙":"1F699","🚚":"1F69A","🚢":"1F6A2","🚤":"1F6A4","🚥":"1F6A5","🚧":"1F6A7","🚨":"1F6A8","🚩":"1F6A9","🚪":"1F6AA","🚫":"1F6AB","🚬":"1F6AC","🚭":"1F6AD","🚲":"1F6B2","🚶":"1F6B6","🚹":"1F6B9","🚺":"1F6BA","🚻":"1F6BB","🚼":"1F6BC","🚽":"1F6BD","🚾":"1F6BE","🛀":"1F6C0","😀":"1F600","😇":"1F607","😈":"1F608","😎":"1F60E","😐":"1F610","😑":"1F611","😕":"1F615","😗":"1F617","😙":"1F619","😛":"1F61B","😟":"1F61F","😦":"1F626","😧":"1F627","😬":"1F62C","😮":"1F62E","😯":"1F62F","😴":"1F634","😶":"1F636","🚁":"1F681","🚂":"1F682","🚆":"1F686","🚈":"1F688","🚊":"1F68A","🚍":"1F68D","🚎":"1F68E","🚐":"1F690","🚔":"1F694","🚖":"1F696","🚘":"1F698","🚛":"1F69B","🚜":"1F69C","🚝":"1F69D","🚞":"1F69E","🚟":"1F69F","🚠":"1F6A0","🚡":"1F6A1","🚣":"1F6A3","🚦":"1F6A6","🚮":"1F6AE","🚯":"1F6AF","🚰":"1F6B0","🚱":"1F6B1","🚳":"1F6B3","🚴":"1F6B4","🚵":"1F6B5","🚷":"1F6B7","🚸":"1F6B8","🚿":"1F6BF","🛁":"1F6C1","🛂":"1F6C2","🛃":"1F6C3","🛄":"1F6C4","🛅":"1F6C5","🌍":"1F30D","🌎":"1F30E","🌐":"1F310","🌒":"1F312","🌖":"1F316","🌗":"1F317","🌘":"1F318","🌚":"1F31A","🌜":"1F31C","🌝":"1F31D","🌞":"1F31E","🌲":"1F332","🌳":"1F333","🍋":"1F34B","🍐":"1F350","🍼":"1F37C","🏇":"1F3C7","🏉":"1F3C9","🏤":"1F3E4","🐀":"1F400","🐁":"1F401","🐂":"1F402","🐃":"1F403","🐄":"1F404","🐅":"1F405","🐆":"1F406","🐇":"1F407","🐈":"1F408","🐉":"1F409","🐊":"1F40A","🐋":"1F40B","🐏":"1F40F","🐐":"1F410","🐓":"1F413","🐕":"1F415","🐖":"1F416","🐪":"1F42A","👥":"1F465","👬":"1F46C","👭":"1F46D","💭":"1F4AD","💶":"1F4B6","💷":"1F4B7","📬":"1F4EC","📭":"1F4ED","📯":"1F4EF","📵":"1F4F5","🔀":"1F500","🔁":"1F501","🔂":"1F502","🔄":"1F504","🔅":"1F505","🔆":"1F506","🔇":"1F507","🔉":"1F509","🔕":"1F515","🔬":"1F52C","🔭":"1F52D","🕜":"1F55C","🕝":"1F55D","🕞":"1F55E","🕟":"1F55F","🕠":"1F560","🕡":"1F561","🕢":"1F562","🕣":"1F563","🕤":"1F564","🕥":"1F565","🕦":"1F566","🕧":"1F567","🔈":"1F508","🚋":"1F68B","➿":"27BF","🇦🇫":"1F1E6-1F1EB","🇦🇱":"1F1E6-1F1F1","🇩🇿":"1F1E9-1F1FF","🇦🇩":"1F1E6-1F1E9","🇦🇴":"1F1E6-1F1F4","🇦🇬":"1F1E6-1F1EC","🇦🇷":"1F1E6-1F1F7","🇦🇲":"1F1E6-1F1F2","🇦🇺":"1F1E6-1F1FA","🇦🇹":"1F1E6-1F1F9","🇦🇿":"1F1E6-1F1FF","🇧🇸":"1F1E7-1F1F8","🇧🇭":"1F1E7-1F1ED","🇧🇩":"1F1E7-1F1E9","🇧🇧":"1F1E7-1F1E7","🇧🇾":"1F1E7-1F1FE","🇧🇪":"1F1E7-1F1EA","🇧🇿":"1F1E7-1F1FF","🇧🇯":"1F1E7-1F1EF","🇧🇹":"1F1E7-1F1F9","🇧🇴":"1F1E7-1F1F4","🇧🇦":"1F1E7-1F1E6","🇧🇼":"1F1E7-1F1FC","🇧🇷":"1F1E7-1F1F7","🇧🇳":"1F1E7-1F1F3","🇧🇬":"1F1E7-1F1EC","🇧🇫":"1F1E7-1F1EB","🇧🇮":"1F1E7-1F1EE","🇰🇭":"1F1F0-1F1ED","🇨🇲":"1F1E8-1F1F2","🇨🇦":"1F1E8-1F1E6","🇨🇻":"1F1E8-1F1FB","🇨🇫":"1F1E8-1F1EB","🇹🇩":"1F1F9-1F1E9","🇨🇱":"1F1E8-1F1F1","🇨🇴":"1F1E8-1F1F4","🇰🇲":"1F1F0-1F1F2","🇨🇷":"1F1E8-1F1F7","🇨🇮":"1F1E8-1F1EE","🇭🇷":"1F1ED-1F1F7","🇨🇺":"1F1E8-1F1FA","🇨🇾":"1F1E8-1F1FE","🇨🇿":"1F1E8-1F1FF","🇨🇩":"1F1E8-1F1E9","🇩🇰":"1F1E9-1F1F0","🇩🇯":"1F1E9-1F1EF","🇩🇲":"1F1E9-1F1F2","🇩🇴":"1F1E9-1F1F4","🇹🇱":"1F1F9-1F1F1","🇪🇨":"1F1EA-1F1E8","🇪🇬":"1F1EA-1F1EC","🇸🇻":"1F1F8-1F1FB","🇬🇶":"1F1EC-1F1F6","🇪🇷":"1F1EA-1F1F7","🇪🇪":"1F1EA-1F1EA","🇪🇹":"1F1EA-1F1F9","🇫🇯":"1F1EB-1F1EF","🇫🇮":"1F1EB-1F1EE","🇬🇦":"1F1EC-1F1E6","🇬🇲":"1F1EC-1F1F2","🇬🇪":"1F1EC-1F1EA","🇬🇭":"1F1EC-1F1ED","🇬🇷":"1F1EC-1F1F7","🇬🇩":"1F1EC-1F1E9","🇬🇹":"1F1EC-1F1F9","🇬🇳":"1F1EC-1F1F3","🇬🇼":"1F1EC-1F1FC","🇬🇾":"1F1EC-1F1FE","🇭🇹":"1F1ED-1F1F9","🇭🇳":"1F1ED-1F1F3","🇭🇺":"1F1ED-1F1FA","🇮🇸":"1F1EE-1F1F8","🇮🇳":"1F1EE-1F1F3","🇮🇩":"1F1EE-1F1E9","🇮🇷":"1F1EE-1F1F7","🇮🇶":"1F1EE-1F1F6","🇮🇪":"1F1EE-1F1EA","🇮🇱":"1F1EE-1F1F1","🇯🇲":"1F1EF-1F1F2","🇯🇴":"1F1EF-1F1F4","🇰🇿":"1F1F0-1F1FF","🇰🇪":"1F1F0-1F1EA","🇰🇮":"1F1F0-1F1EE","🇽🇰":"1F1FD-1F1F0","🇰🇼":"1F1F0-1F1FC","🇰🇬":"1F1F0-1F1EC","🇱🇦":"1F1F1-1F1E6","🇱🇻":"1F1F1-1F1FB","🇱🇧":"1F1F1-1F1E7","🇱🇸":"1F1F1-1F1F8","🇱🇷":"1F1F1-1F1F7","🇱🇾":"1F1F1-1F1FE","🇱🇮":"1F1F1-1F1EE","🇱🇹":"1F1F1-1F1F9","🇱🇺":"1F1F1-1F1FA","🇲🇰":"1F1F2-1F1F0","🇲🇬":"1F1F2-1F1EC","🇲🇼":"1F1F2-1F1FC","🇲🇾":"1F1F2-1F1FE","🇲🇻":"1F1F2-1F1FB","🇲🇱":"1F1F2-1F1F1","🇲🇹":"1F1F2-1F1F9","🇲🇭":"1F1F2-1F1ED","🇲🇷":"1F1F2-1F1F7","🇲🇺":"1F1F2-1F1FA","🇲🇽":"1F1F2-1F1FD","🇫🇲":"1F1EB-1F1F2","🇲🇩":"1F1F2-1F1E9","🇲🇨":"1F1F2-1F1E8","🇲🇳":"1F1F2-1F1F3","🇲🇪":"1F1F2-1F1EA","🇲🇦":"1F1F2-1F1E6","🇲🇿":"1F1F2-1F1FF","🇲🇲":"1F1F2-1F1F2","🇳🇦":"1F1F3-1F1E6","🇳🇷":"1F1F3-1F1F7","🇳🇵":"1F1F3-1F1F5","🇳🇱":"1F1F3-1F1F1","🇳🇿":"1F1F3-1F1FF","🇳🇮":"1F1F3-1F1EE","🇳🇪":"1F1F3-1F1EA","🇳🇬":"1F1F3-1F1EC","🇰🇵":"1F1F0-1F1F5","🇳🇴":"1F1F3-1F1F4","🇴🇲":"1F1F4-1F1F2","🇵🇰":"1F1F5-1F1F0","🇵🇼":"1F1F5-1F1FC","🇵🇦":"1F1F5-1F1E6","🇵🇬":"1F1F5-1F1EC","🇵🇾":"1F1F5-1F1FE","🇵🇪":"1F1F5-1F1EA","🇵🇭":"1F1F5-1F1ED","🇵🇱":"1F1F5-1F1F1","🇵🇹":"1F1F5-1F1F9","🇶🇦":"1F1F6-1F1E6","🇹🇼":"1F1F9-1F1FC","🇨🇬":"1F1E8-1F1EC","🇷🇴":"1F1F7-1F1F4","🇷🇼":"1F1F7-1F1FC","🇰🇳":"1F1F0-1F1F3","🇱🇨":"1F1F1-1F1E8","🇻🇨":"1F1FB-1F1E8","🇼🇸":"1F1FC-1F1F8","🇸🇲":"1F1F8-1F1F2","🇸🇹":"1F1F8-1F1F9","🇸🇦":"1F1F8-1F1E6","🇸🇳":"1F1F8-1F1F3","🇷🇸":"1F1F7-1F1F8","🇸🇨":"1F1F8-1F1E8","🇸🇱":"1F1F8-1F1F1","🇸🇬":"1F1F8-1F1EC","🇸🇰":"1F1F8-1F1F0","🇸🇮":"1F1F8-1F1EE","🇸🇧":"1F1F8-1F1E7","🇸🇴":"1F1F8-1F1F4","🇿🇦":"1F1FF-1F1E6","🇱🇰":"1F1F1-1F1F0","🇸🇩":"1F1F8-1F1E9","🇸🇷":"1F1F8-1F1F7","🇸🇿":"1F1F8-1F1FF","🇸🇪":"1F1F8-1F1EA","🇨🇭":"1F1E8-1F1ED","🇸🇾":"1F1F8-1F1FE","🇹🇯":"1F1F9-1F1EF","🇹🇿":"1F1F9-1F1FF","🇹🇭":"1F1F9-1F1ED","🇹🇬":"1F1F9-1F1EC","🇹🇴":"1F1F9-1F1F4","🇹🇹":"1F1F9-1F1F9","🇹🇳":"1F1F9-1F1F3","🇹🇷":"1F1F9-1F1F7","🇹🇲":"1F1F9-1F1F2","🇹🇻":"1F1F9-1F1FB","🇺🇬":"1F1FA-1F1EC","🇺🇦":"1F1FA-1F1E6","🇦🇪":"1F1E6-1F1EA","🇺🇾":"1F1FA-1F1FE","🇺🇿":"1F1FA-1F1FF","🇻🇺":"1F1FB-1F1FA","🇻🇦":"1F1FB-1F1E6","🇻🇪":"1F1FB-1F1EA","🇻🇳":"1F1FB-1F1F3","🇪🇭":"1F1EA-1F1ED","🇾🇪":"1F1FE-1F1EA","🇿🇲":"1F1FF-1F1F2","🇿🇼":"1F1FF-1F1FC","🇵🇷":"1F1F5-1F1F7","🇰🇾":"1F1F0-1F1FE","🇧🇲":"1F1E7-1F1F2","🇵🇫":"1F1F5-1F1EB","🇵🇸":"1F1F5-1F1F8","🇳🇨":"1F1F3-1F1E8","🇸🇭":"1F1F8-1F1ED","🇦🇼":"1F1E6-1F1FC","🇻🇮":"1F1FB-1F1EE","🇭🇰":"1F1ED-1F1F0","🇦🇨":"1F1E6-1F1E8","🇲🇸":"1F1F2-1F1F8","🇬🇺":"1F1EC-1F1FA","🇬🇱":"1F1EC-1F1F1","🇳🇺":"1F1F3-1F1FA","🇼🇫":"1F1FC-1F1EB","🇲🇴":"1F1F2-1F1F4","🇫🇴":"1F1EB-1F1F4","🇫🇰":"1F1EB-1F1F0","🇯🇪":"1F1EF-1F1EA","🇦🇮":"1F1E6-1F1EE","🇬🇮":"1F1EC-1F1EE"},a.shortnameRegexp=":([-+\\w]+):",a.imagePathPNG="//cdn.jsdelivr.net/emojione/assets/png/",a.imagePathSVG="//cdn.jsdelivr.net/emojione/assets/svg/",a.imagePathSVGSprites="./../assets/sprites/emojione.sprites.svg",a.imageType="png",a.sprites=!1,a.unicodeAlt=!0,a.ascii=!1,a.cacheBustParam="?v=1.2.4",a.toImage=function(b){return b=a.unicodeToImage(b),b=a.shortnameToImage(b)},a.unifyUnicode=function(b){return b=a.toShort(b),b=a.shortnameToUnicode(b)},a.shortnameToAscii=function(b){var c,d=a.objectFlip(a.asciiList);return b=b.replace(new RegExp("<object[^>]*>.*?</object>|<span[^>]*>.*?</span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+a.shortnameRegexp+")","gi"),function(b){return"undefined"!=typeof b&&""!==b&&b in a.emojioneList?(c=a.emojioneList[b][a.emojioneList[b].length-1].toLowerCase(),"undefined"!=typeof d[c]?d[c]:b):b})},a.shortnameToUnicode=function(b){var c;return b=b.replace(new RegExp("<object[^>]*>.*?</object>|<span[^>]*>.*?</span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+a.shortnameRegexp+")","gi"),function(b){return"undefined"!=typeof b&&""!==b&&b in a.emojioneList?(c=a.emojioneList[b][a.emojioneList[b].length-1].toUpperCase(),a.convert(c)):b}),a.ascii&&(b=b.replace(new RegExp("<object[^>]*>.*?</object>|<span[^>]*>.*?</span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|((\\s|^)"+a.asciiRegexp+"(?=\\s|$|[!,.]))","g"),function(b,d,e,f){return"undefined"!=typeof f&&""!==f&&a.unescapeHTML(f)in a.asciiList?(f=a.unescapeHTML(f),c=a.asciiList[f].toUpperCase(),e+a.convert(c)):b})),b},a.shortnameToImage=function(b){var c,d,e;return b=b.replace(new RegExp("<object[^>]*>.*?</object>|<span[^>]*>.*?</span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+a.shortnameRegexp+")","gi"),function(b){return"undefined"!=typeof b&&""!==b&&b in a.emojioneList?(d=a.emojioneList[b][a.emojioneList[b].length-1].toUpperCase(),e=a.unicodeAlt?a.convert(d):b,c="png"===a.imageType?a.sprites?'<span class="emojione-'+d+'" title="'+b+'">'+e+"</span>":'<img class="emojione" alt="'+e+'" src="'+a.imagePathPNG+d+".png"+a.cacheBustParam+'"/>':a.sprites?'<svg class="emojione"><description>'+e+'</description><use xlink:href="'+a.imagePathSVGSprites+"#emoji-"+d+'"></use></svg>':'<object class="emojione" data="'+a.imagePathSVG+d+".svg"+a.cacheBustParam+'" type="image/svg+xml" standby="'+e+'">'+e+"</object>"):b}),a.ascii&&(b=b.replace(new RegExp("<object[^>]*>.*?</object>|<span[^>]*>.*?</span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|((\\s|^)"+a.asciiRegexp+"(?=\\s|$|[!,.]))","g"),function(b,f,g,h){return"undefined"!=typeof h&&""!==h&&a.unescapeHTML(h)in a.asciiList?(h=a.unescapeHTML(h),d=a.asciiList[h].toUpperCase(),e=a.unicodeAlt?a.convert(d):a.escapeHTML(h),c="png"===a.imageType?a.sprites?g+'<span class="emojione-'+d.toUpperCase()+'" title="'+a.escapeHTML(h)+'">'+e+"</span>":g+'<img class="emojione" alt="'+e+'" src="'+a.imagePathPNG+d+".png"+a.cacheBustParam+'"/>':a.sprites?'<svg class="emojione"><description>'+e+'</description><use xlink:href="'+a.imagePathSVGSprites+"#emoji-"+d.toUpperCase()+'"></use></svg>':g+'<object class="emojione" data="'+a.imagePathSVG+d+".svg"+a.cacheBustParam+'" type="image/svg+xml" standby="'+e+'">'+e+"</object>"):b})),b},a.unicodeToImage=function(b){var c,d,e;if(!a.unicodeAlt||a.sprites)var f=a.mapShortToUnicode();return b=b.replace(new RegExp("<object[^>]*>.*?</object>|<span[^>]*>.*?</span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+a.unicodeRegexp+")","gi"),function(b){return"undefined"!=typeof b&&""!==b&&b in a.jsecapeMap?(d=a.jsecapeMap[b],e=a.unicodeAlt?a.convert(d):f[d],c="png"===a.imageType?a.sprites?'<span class="emojione-'+d.toUpperCase()+'" title="'+f[d]+'">'+e+"</span>":'<img class="emojione" alt="'+e+'" src="'+a.imagePathPNG+d+".png"+a.cacheBustParam+'"/>':a.sprites?'<svg class="emojione"><description>'+e+'</description><use xlink:href="'+a.imagePathSVGSprites+"#emoji-"+d.toUpperCase()+'"></use></svg>':'<img class="emojione" alt="'+e+'" src="'+a.imagePathSVG+d+".svg"+a.cacheBustParam+'"/>'):b})},a.toShort=function(b){for(var c in a.emojioneList)if(a.emojioneList.hasOwnProperty(c))for(var d in a.emojioneList[c])if(a.emojioneList[c].hasOwnProperty(d)){var e=a.emojioneList[c][d].toUpperCase();b=a.replaceAll(b,a.convert(e),c)}return b},a.convert=function(a){if(a.indexOf("-")>-1){for(var b=[],c=a.split("-"),d=0;d<c.length;d++){var e=parseInt(c[d],16);if(e>=65536&&1114111>=e){var f=Math.floor((e-65536)/1024)+55296,g=(e-65536)%1024+56320;e=String.fromCharCode(f)+String.fromCharCode(g)}else e=String.fromCharCode(e);b.push(e)}return b.join("")}var c=parseInt(a,16);if(c>=65536&&1114111>=c){var f=Math.floor((c-65536)/1024)+55296,g=(c-65536)%1024+56320;return String.fromCharCode(f)+String.fromCharCode(g)}return String.fromCharCode(c)},a.escapeHTML=function(a){var b={"&":"&","<":"<",">":">",'"':""","'":"'"};return a.replace(/[&<>"']/g,function(a){return b[a]})},a.unescapeHTML=function(a){var b={"&":"&","&":"&","&":"&","<":"<","<":"<","<":"<",">":">",">":">",">":">",""":'"',""":'"',""":'"',"'":"'","'":"'","'":"'"};return a.replace(/&(?:amp|#38|#x26|lt|#60|#x3C|gt|#62|#x3E|apos|#39|#x27|quot|#34|#x22);/gi,function(a){return b[a]})},a.mapShortToUnicode=function(){var b={};for(var c in a.emojioneList)if(a.emojioneList.hasOwnProperty(c))for(var d in a.emojioneList[c])a.emojioneList[c].hasOwnProperty(d)&&(b[a.emojioneList[c][d].toUpperCase()]=c);return b},a.objectFlip=function(a){var b,c={};for(b in a)a.hasOwnProperty(b)&&(c[a[b]]=b);return c},a.escapeRegExp=function(a){return a.replace(/[-[\]{}()*+?.,;:&\\^$|#\s]/g,"\\$&")},a.replaceAll=function(a,b,c){var d=new RegExp("<object[^>]*>.*?</object>|<span[^>]*>.*?</span>|<(?:object|embed|svg|img|div|span|p|a)[^>]*>|("+b+")","gi"),e=function(a,b){return"undefined"==typeof b||""===b?a:c};return a.replace(d,e)}}(this.emojione=this.emojione||{}),"object"==typeof module&&(module.exports=this.emojione); | alexmojaki/cdnjs | ajax/libs/emojione/1.4.1/lib/js/emojione.min.js | JavaScript | mit | 74,987 |
AmCharts.maps.finlandLow={svg:{defs:{"amcharts:ammap":{projection:"mercator",leftLongitude:"19.478882",topLatitude:"70.093113",rightLongitude:"31.590203",bottomLatitude:"59.808736"}},g:{path:[{id:"FI-01",title:"Åland Islands",d:"M47.27,778.6l0.59,0.58l-0.65,-0.05l-0.67,0.84l-0.42,-0.46l0.06,-0.8L47.27,778.6zM44.28,779.13l0.7,0.9l0.7,0.17l0.09,0.38l0.76,0.03l0.11,-0.37l-0.51,-0.06l0.17,-0.26l-0.35,-0.2l0.2,-0.49l-0.31,-1.27l-1.25,0.39L44.28,779.13zM46.1,777.79l0.68,0.79l0.66,-0.08l0.73,0.53l-0.26,0.29l0.36,0.25l0.5,-0.17l-0.25,-1.1l-0.83,-0.04l-0.26,-0.54l1.52,0.34l0.12,-0.62l-0.22,0.13l-0.21,-0.35l-0.41,0.32l-0.43,-0.52l-0.54,0.17l-0.31,-0.4l-0.56,-0.03l-0.37,0.41L46.1,777.79zM31.27,775.2l0.22,-1.14l-0.79,-0.64l-1.2,0.12l1.36,1.65L31.27,775.2zM27.35,773.86l-0.29,0.37l-0.79,0.93l0.19,0.43l0.33,0.17l0.29,-0.38l0.26,0.34l0.44,-0.95l0.35,0.28l0.25,-0.68l0.38,0.19l-0.4,0.32l0.13,0.7l0.79,0.18l-0.05,-0.45l0.88,0.19l0.04,-0.74l-0.82,-1.23l-0.38,-0.16l0.03,0.38l-0.75,-0.76l-0.75,0.29L27.35,773.86zM16.41,772.62l-0.14,0.37l1.07,0.88l0.28,-0.59l-0.37,-0.56l-1.69,-0.6l0.11,0.42L16.41,772.62zM16.35,772.15l0.08,-1.14l-0.99,0.82L16.35,772.15zM34.49,770.41l-0.73,0.58l0.24,0.6l-1.22,1.39l0.29,0.86l0.23,0.25l1.23,-0.21l-0.21,-0.63l0.63,-0.56l-0.11,0.92l1.26,-0.46l0.08,-0.87l0.3,-0.13l-0.38,-0.49l-0.61,0.13l-0.21,-0.67l0.66,-0.48l-0.62,-0.28l-0.14,0.56L34.49,770.41zM32.9,770.37l-0.94,0.34l-0.32,0.91l0.34,0.24l-0.53,0.89l0.06,0.75l0.54,0.03l-0.15,-0.22l0.77,-0.58l-0.33,-0.24l1.27,-0.81l-0.24,-0.64l0.34,-0.22l0.19,-0.2l0.24,-0.12l-0.11,-0.28l-0.89,0.38L32.9,770.37zM29.84,771.78l-0.92,0.86l0.08,0.4l1.14,0.13l0.13,-0.33L31,772.8l1.05,-2.62L31.73,770l-1.42,0.75L29.84,771.78zM27.84,769.8l0.17,0.23l0.18,-0.55l-0.38,-0.76l-0.4,1.37L27.84,769.8zM31.2,768.95l0.45,0.22l0.73,-0.36l1.08,0.08l-0.95,-0.64l-0.96,-0.04l0.07,0.35L31.2,768.95zM36.02,768.94l0.29,-0.26l-0.5,-0.31l0.4,-0.51l-0.41,-0.18l-0.47,0.54l0.11,0.36L36.02,768.94zM34.01,768.33l0.92,0.07l-0.04,-0.47l0.3,-0.14l-0.14,-0.4l-1.11,0.21l0.04,-0.29l-0.58,-0.19l-0.27,0.52l-0.02,-0.49l-0.9,0.38L34.01,768.33zM37.23,765.84l0.86,1.29l0.68,0.24l0.23,-1.08l-0.58,-1.4l-0.83,-0.28l-0.43,0.56L37.23,765.84zM24,764.76l0.58,1.06l-0.65,0.21l0.14,0.83l-0.5,0.53l-0.22,0.94l0.08,0.28l0.66,-0.12l0.13,0.51l0.75,0.31l-0.32,0.75l0.52,0.23l0.9,-0.9l-0.33,-0.67l0.05,-1.3l0.31,0.16l0.5,-0.47l-0.46,-0.34l0.27,-1.9l-1.29,-1.12l0.21,0.62l-0.32,0.83l-0.12,-0.98l-0.58,-0.62l-0.2,0.79L24,764.76zM36.35,764l-0.02,-0.52l-0.84,0.17L35,764.27L36.35,764zM27.01,764.04l0.33,0.29l0.82,-0.52l-0.11,-0.88l-0.52,0.53L27.01,764.04zM30.32,763.34l-0.82,0.83l1.23,-0.17l0.41,-0.86l-0.33,-0.53l-0.32,0.03L30.32,763.34zM25.68,761.37l-0.01,0.5l-0.75,0.54l0.27,0.71l0.64,-0.39l0.27,-1.25l0.93,-0.02l0.06,-1.61l-0.57,0.04l-0.33,1L25.68,761.37zM38.25,760.83l-0.29,0.24l0.2,0.59l0.53,-0.25l-0.24,0.48l0.24,0.33l0.5,-0.39l0.51,0.11l0.18,-0.47l-0.42,-1.41l-0.53,-0.41l0,0.39l-0.56,-0.67l-0.24,0.96L38.25,760.83zM28.01,756.54l0.03,0.54l-0.12,0.75l-0.71,0.19l0.33,1.11l-0.18,0.36l0.48,0.21l0.44,-0.54l0.58,0.03l-0.46,0.45l0.44,0.34l0.07,1.81l0.63,-0.39l0.18,-0.82l-0.39,-0.15l0.79,-0.29l0.55,-1.96l-0.37,-0.32l-0.51,0.15l0.09,-0.73l-2.18,-1.4l-0.47,0.3l0.38,0.39L28.01,756.54zM41.4,756.67l-0.2,0.17l-0.84,0.42l-0.02,0.57l1.03,0.84l0.02,0.75l1.34,0.59l-0.14,-1.17l0.3,0.17l0.62,-0.57l-0.03,-1.43l-0.99,-0.82l-0.08,-0.44l-0.67,-0.05L41.4,756.67zM33.13,756.46l0.33,-0.3l-0.42,-1.13l-0.36,0.55L33.13,756.46zM28.65,754.82l0.73,1.06l-0.24,0.71l0.65,0.32l0.1,-2.07l-0.98,-0.23L28.65,754.82zM30.53,754.38l-0.3,0.82l0.76,-0.47l0.3,0.24v-1.14l-0.39,0.5L30.53,754.38zM47.94,753.23l0.08,0.54l-0.68,0.26l0.61,0.33l-0.12,0.34l0.64,0.57l0.33,-2.19l-0.28,-0.26l-0.19,0.57L47.94,753.23zM46.56,754.49l0.4,-0.31l-0.09,-0.92l-0.71,-1.53l-0.38,0.65L46.56,754.49zM27.65,752.26l0.99,0.58l0.66,-0.33l-0.01,-0.75l-0.85,-0.16l-0.12,-0.32l-0.54,0.03l0.13,0.6L27.65,752.26zM26.84,752.79l0.3,0.24l0.32,-0.52l0.22,-1.51l-0.28,-0.14l-1.17,1.26l0.34,0.92L26.84,752.79zM50.82,752.12l1.07,0.75l0.17,-0.25l-0.74,-0.7l0.32,-0.15l-0.91,-1.06l-0.18,0.21L50.82,752.12zM40.31,752.88l0.17,1.34l0.88,-1.02l0.5,0.12l0.32,-0.57l-0.13,-0.69l0.29,-0.38l-0.36,-0.84l-0.98,-0.26l0.26,0.55L40.31,752.88zM20.8,750.31l0.31,-1.13l-0.82,0.59L20.8,750.31zM20.06,749.82l0.53,-0.59l0.12,-0.89l-0.62,0.03l-0.62,0.93L20.06,749.82zM50.16,748.64l0.25,-0.52l-0.03,0.84l0.65,-0.16l0.12,-1.09l-0.83,-0.71l-0.39,0.58L50.16,748.64zM11.55,747.96l-0.51,-0.55l-0.6,1.4l-0.04,0.67l0.6,0.79l-0.79,-0.15l-0.43,0.99l0.31,-0.16l0.28,0.37l-0.09,0.99l-0.34,0.25l0.8,0.75l0.32,-1.07l-0.49,-0.24l0.31,-0.65l-0.44,-0.26l0.49,-0.14l0.4,0.52l0.42,1.98h1.06l0.52,-0.97l0.73,0.75l-0.05,0.48l-0.67,0.25l0.49,0.35l-0.6,0.63l-0.11,-1.44l-0.71,0.11l-0.48,0.54l0.39,0.13l0.09,0.57l0.27,-0.52l0.11,1.6l0.81,-0.99l0.04,1.36l-0.35,0.82l-0.69,0.14l0.09,0.82l-1.25,0.82l0.12,-1.84l-0.68,0.39l0.2,1.4l-0.43,0.65l0.83,0.44L11,760.17l0.17,1.36l-0.54,0.11l-0.36,-3.22l-0.81,-1.03l1.08,-3.04l0.32,-0.12l-0.17,-0.59l-1.6,-0.94l-0.4,0.23l0.36,0.77l-0.31,0.39l0.3,0.95l-0.51,1.16l-0.19,-0.88l-0.46,-0.03l-0.52,0.65l-0.71,-0.73l-0.67,-0.04l0.06,-0.35l-0.75,0.79l0.54,0.95l0.22,-0.11l0.21,1.15l-0.24,0.85l1.14,1.9l-0.23,1.21l1.01,3.31l-0.15,0.34l0.59,0.89l0.01,0.93l0.68,0.92l-0.13,0.37l0.52,0.25l0.5,-0.17l0.05,-0.74l0.37,-0.38l0.45,0.25l0.23,1.08l0.58,-0.2l0.17,0.44l0.47,-0.64l0.53,0.41l0.45,-0.56l0.81,1.23l0.44,-2.55l0.33,2.59l0.75,1.16l0.18,-1.51l-0.52,-1.75l0.73,-0.13l0.57,2.33l-0.35,0.35l0.27,0.33l0.33,-0.36l0.73,0.17l0.89,1.92l0.19,-0.43l0.52,0.44l0.05,-0.47l0.5,-0.24l0.87,1.53l0.14,1.85l0.72,-0.34l0.01,0.63l0.66,-0.24l-0.14,-0.5l0.54,-0.79l0.38,1.47l-0.17,0.42l0.35,0.17l-0.48,0.24l0.18,0.79l0.84,-0.83l-0.33,-0.34l0.41,-0.06l-0.04,-0.52l0.82,-0.6l-0.91,-1.36l0.5,-2.37l-0.47,-0.03l0.56,-0.46l0.02,-0.68l-0.41,-0.49l-0.56,0.64l-0.69,-0.66l-1.22,0.03l-1.51,-1.34l-0.38,1.44l-0.53,-0.51l0.04,0.67l-0.61,0.22l-0.71,-1.27l0.78,-0.04l0.24,-1.08l-0.4,-0.58l-0.5,0.26l-0.1,-1.58l0.49,-0.03l-0.04,-1.8l0.36,-0.76l-0.3,-0.22l-0.75,0.38l-0.19,1.35l-0.27,-0.84l0.5,-0.98l-0.41,-0.75l0.47,-0.67l-0.01,-1.38l0.59,0.08l0.41,0.71l-0.5,0.75l0.4,0.85l0.45,0.33l0.21,-0.34l0.54,0.98l0.42,0.09l0.85,-0.93l0.16,0.69l1.33,0.87l0.39,-0.26l0.35,-1.47l1.35,-0.1l0.25,-0.51l0.58,0.54l0.45,-0.34l0.33,-0.87l-0.77,-0.23l-0.49,0.42l-1.04,-1.72l0.22,-0.26l0.7,0.94l0.47,-0.99l-0.19,-1.08l0.84,-1.19l-0.58,-0.01l-0.39,-0.55l-1.25,-0.41l-0.25,0.14l-0.44,0.23l-0.14,-0.3l1.02,-1.79l-0.25,-0.44l-0.48,0.43l0.12,-1.1l-0.53,-0.18l0.07,0.4l-1.07,-0.64l0.48,1.33l-1.02,-0.75l0.33,-0.14v-0.5l-0.57,0.48l-0.23,-0.56l-0.47,-0.15l0.25,-0.52l0.38,0.21l0.08,-0.54l-1.29,-0.34l-0.88,0.17l-0.89,-0.43l-0.4,0.53l-0.94,-0.34l-0.9,0.45l-0.57,-0.48l0.75,-1.57l-0.36,-0.17L14.67,749v-1.32l-0.33,0.34l-0.1,-0.82l-2.11,-0.15L11.55,747.96zM51.65,743.38l-0.41,0.09l-0.07,0.78l-0.33,-0.48l-0.23,0.69l0.51,0.39l-0.15,0.5l0.75,0.29l0.38,-0.88l-0.16,-0.47l0.36,-0.32l-0.23,-0.65l-0.24,0.47L51.65,743.38zM50.17,742.66l0.45,0.04l0.47,0.67l0.75,-0.14l-0.51,-0.78l-0.28,-0.08l-0.8,-0.53l-0.27,0.21L50.17,742.66zM0.2,759.02l0.47,0.05l0.21,0.21L1.91,759l0.27,0.32l-0.12,-0.88l-0.22,0.21l-0.33,-0.68l0.5,-0.47l-0.74,-0.05l-0.31,0.69l-0.54,0.12l0.25,-1.15H0.32L0.2,759.02zM4.27,755.07l-1.33,2.63l-0.78,-0.11l0.06,3.13l-0.51,-0.03l-0.24,0.82l0.03,1.89l0.5,0.44l0.31,1.03l0.53,-0.11l0.51,0.42l0.96,-0.47l-0.44,-1.11l0.06,-0.79l0.52,-0.52l-0.59,-0.26l-0.14,-2.02l0.63,1.89l0.51,-0.23l-0.27,0.97l0.6,0.3l0.12,0.65l0.57,0.23l0.38,-0.39l0.38,-1.68l-0.12,-1.92l-0.73,-0.19l-0.42,-0.72l0.44,-1.2l-0.39,-0.61l-0.43,0.13l-0.71,-2.94L4.27,755.07zM12.12,754.54l-0.48,0.06l-0.16,-0.7l-0.8,1.35l0.68,1.66L12.12,754.54zM3.49,751.47l-0.21,1.01l0.44,0.23l0.18,0.61l0.44,-1.88l0.56,-0.9L3.49,751.47zM8.6,751.28l0.33,-0.35l0.29,0.19l0.28,-0.79l-1.07,0.44L8.6,751.28zM7.6,751.33l0.14,-0.42l-0.67,-1.11l-0.12,0.95L7.6,751.33zM7.48,749.71l0.47,0.85l0.61,-0.32l-0.04,-1.13l-0.73,-0.13l0.01,0.48L7.48,749.71zM9.89,749.79l0.26,-1.42l-0.28,-0.46l-0.29,0.64l-0.25,-0.39l0.28,-1.36l-0.56,0.06l-0.09,0.8L9.89,749.79zM33.82,768.87l-0.11,0.55l1.29,-0.28l-0.26,-0.48l-1.73,-0.39L33.82,768.87zM6.48,763.15l0.23,0.79l0.43,-0.98l-0.16,-0.42L6.48,763.15zM40.36,760.36l0.38,-0.57l-0.4,-0.71l0.11,-0.93l-0.34,0.14l-0.1,1.11L40.36,760.36zM44.41,759.27l0.21,-1.02l-0.35,-0.88l-0.56,0.86L44.41,759.27zM40.56,755.47l0.73,0.26l0.01,-0.62l-0.95,-0.06L40.56,755.47zM50.82,755.71l0.22,-0.39l-0.51,-0.77l-0.64,0.13L50.82,755.71zM7.34,753.5l-0.06,0.65l0.24,-0.33l0.57,0.1l-0.2,-0.82l-0.33,0.45L7.34,753.5zM29.63,752.67l0.08,0.34l0.26,-0.08l0.55,-0.6l-1,-0.43L29.63,752.67zM7,753.39l0.3,-0.59l-0.11,-1.05l-0.65,0.74L7,753.39zM8.75,751.48l0.94,0.53l0.25,-0.65l-0.33,0.14l-0.29,-0.5l-0.11,0.24L8.75,751.48zM15.8,750.36l0.5,-0.45l-0.6,-0.31l-0.32,0.5L15.8,750.36zM18,749.86l0.08,-0.29l0.62,0.37l-0.11,-0.52l-0.63,-0.29l-0.24,0.61L18,749.86zM16.74,750.11l0.04,-0.71l-0.36,-0.26l0.2,-0.74l-0.61,0.73L16.74,750.11zM41.24,748.91l0.79,0.99L41.92,749l-0.36,-0.29l0.31,-0.39l-0.25,-0.41l-0.42,0.19L41.24,748.91zM36.06,748.42l0.7,0.46l0.31,-0.4l-0.4,-0.96l-0.46,-0.03l0.28,0.49L36.06,748.42zM48.5,748.23l0.2,-0.71l0.22,0.08l-0.09,-0.86l-0.99,0.5L48.5,748.23zM49.21,746.11l-0.08,0.23l0.85,0.57l0.37,-0.59L49.21,746.11zM18.08,746.66l0.24,0.28l0.09,-0.37l0.33,0.12l0.26,0.77l0.15,-1.38l-0.78,0.05L18.08,746.66zM46.66,744.72l-0.14,1.22l0.74,0.19l0.19,-1.28l-0.37,-0.29l0.08,-0.4l-0.26,0.19l-0.53,-0.69l-0.11,0.36L46.66,744.72zM50.96,741.19l1.06,0.16l0.05,-0.77l-0.5,-0.19l0.1,-0.36l-1.01,-0.03l-0.43,0.41L50.96,741.19zM50.29,739.14l-0.08,0.56l0.78,-1.04l-1.33,-0.06l0.13,0.32L50.29,739.14z"},{id:"FI-02",title:"South Karelia",d:"M332.27,664.98L331.77,665L330.94,666.01L330.65,667.27L328.87,669.52L328.47,671.23L324.11,676.34L322.55,676.91L320.63,676.96L320.79,679.01L315.04,686.56L312.43,691.31L312.5,691.7L304.55,697.83L303.32,699.55L300.97,700.23L298.93,701.66L298.46,703.47L295.58,706.64L294.57,710.88L293.6,712.95L292.33,712.54L290.99,712.77L289.45,712.47L288.09,714.49L287.48,714.72L283.46,719.11L283.08,718.92L282.64,720.04L279.72,723.84L278.19,724.17L277.02,726.61L272.46,731.3L272.46,731.3L271.23,731.44L271.21,730.2L269.56,729.45L268.27,726.84L267.91,725.01L266.08,724.75L265.45,725.42L264.18,725.27L263.46,723.49L263.57,723.01L262.42,722.59L260.25,722.36L258.25,722.85L256.89,722.77L255.21,721.32L252.63,717.51L247.64,715.91L245.1,712.8L244.66,712.02L244.94,711.76L245.64,712.7L246.5,712.86L248.65,711.81L247.84,711.09L247.41,709.09L246.25,709.75L245.25,708.93L245.84,707.76L245.43,706.44L245.5,705.08L246.59,703.97L248.18,703.65L247.25,702.67L246.78,703.03L246.43,702.63L247.66,700.32L247.37,698.9L247.37,698.9L249.47,698.65L250.5,697.96L250.93,698.48L252.13,698.22L252.39,697.84L252.3,696.8L253.2,696.33L253.13,695.65L252.32,695.82L251.25,694.88L251.2,693.88L251.96,693.33L250.67,691.57L250.13,689.77L249.85,689.97L248.36,689.34L247.85,688.67L249.14,688.73L249.21,688.14L247.64,687.67L246.32,688.08L245.46,687.88L245.34,688.59L243.45,687.63L241.93,686.36L240.52,686.8L239.38,686.64L239.59,685.99L240.79,685.33L241.47,684.03L243.15,684.38L243.73,685.12L244.23,685.2L245.18,685.04L246.08,683.02L249.3,682.82L249.88,683.18L250.52,682.88L252.5,683.24L254.61,684.28L255.74,684.34L257.42,685.29L258.43,685.48L259.07,686.1L262.24,686.08L264.77,685.13L268.05,686.38L270.43,686.44L274.59,686.13L280.84,684.48L281.27,684.67L281.13,684.16L281.9,683.72L282.63,682.02L283.67,682.04L283.76,681L286.41,679.29L286.21,677.32L286.89,675.6L287.57,676.39L288.45,675.48L289.54,676.5L289.54,677.8L291.29,677.88L291.77,678.46L293.45,678.16L293.58,678.71L295.69,677.55L298.13,677.85L298.16,676.75L298.79,676.2L298.95,673.94L301.15,674.54L303.37,673.69L306.28,674.11L311.67,672.43L313.04,672.54L313.94,670.16L317.52,666.25L322,664.05L322.63,661.51L322.63,661.51L339.79,652.44L340.93,651.92L341.31,652.74L341.31,652.74L339.03,654.99L337.99,658.57L332.53,664.18z"},{id:"FI-03",title:"Southern Ostrobothnia",d:"M69.63,641.25L69,639.87L69.71,638.53L68.93,635.83L69.46,634.82L69.42,632.44L70.22,632.96L70.66,632.52L70.65,633.11L71.08,632.8L71.39,631.21L70.17,629.85L71.52,628.09L73.39,627.72L72.14,625.27L71.01,624.41L70.84,624.93L70.36,624.87L70.65,620.77L70.21,620.14L70.74,619.45L70.8,618.43L69.57,617.55L68.89,617.75L68.74,618.14L68.69,617.78L66.74,618.15L66.27,617.09L65.62,616.69L66.48,615.54L66.33,612.56L65.2,611.69L65.44,611.36L66.29,611.95L68.41,605.52L68.5,604.4L67.98,604.27L67.8,601.08L68.87,600.62L69.62,599.82L69.84,598.84L70.85,598.41L71.22,597.46L72.12,596.86L72.68,594.88L72.88,595.3L72.61,595.99L72.91,596.11L74.23,594.88L72.82,592.97L72.26,590.57L72.24,586.08L73.36,584.26L73.61,583.11L75.49,584.36L75.83,586.24L76.26,586.12L76.35,586.66L77.01,587.16L82.84,590.02L83.05,589.72L84.7,590.27L84.83,589.83L87.24,590.9L89.64,588.12L90.57,587.81L92.77,583.49L93.85,582.88L93.24,579.65L93.92,579.53L93.87,578.82L94.52,577.41L94.14,576.84L95.6,574.97L96.08,572.61L97.58,570.48L97.34,570.4L97.55,570.02L97.87,570.23L98.34,569.69L98.52,570.15L98.73,569.93L97.93,568.86L100,567.49L100.69,568.38L100.97,567.61L99.81,567.32L101.29,566.69L101.14,566.28L101.66,565.98L101.55,564.67L101.07,564.41L101.94,564.29L102.59,564.67L102.46,559.93L100.75,560.78L100.46,560.22L99.3,560.74L99.93,559.27L101.1,558.61L100.43,557.31L100.11,557.27L100.51,556.7L98.7,555.56L98.86,554.67L100,553.44L100.38,553.77L102.5,552.46L101.69,551.04L103.91,549.63L104.17,549.98L105.11,549.31L104.73,548.4L104.07,548.74L104.02,548.28L105.39,548.17L105.92,548.74L106.7,548.25L107.6,548.69L107.43,548.97L108.92,548.93L108.47,548.5L108.56,548.25L108.9,548.42L108.74,547.7L109.62,548.05L109.14,548.43L112.29,549.93L112.04,547.22L112.96,547.26L112.89,546.73L113.71,546.63L114.05,547.88L115.57,547.53L116.52,548.82L119.5,545.22L120.48,541.68L121.3,540.13L125.41,538.1L126.26,539.22L127.89,539.51L129.46,540.56L129.82,540.14L130.19,540.27L130.91,541.67L130.68,542.1L132.03,543.53L131.88,543.79L132.94,545.18L135.17,546.59L135.17,546.59L137.41,551.33L140.22,553.88L143.36,554L145.39,554.58L147.93,556.21L150.19,558.42L152.36,561.44L151.63,562.07L151.52,561.46L150.9,561.88L150.93,562.26L150.49,562.16L150.17,563.1L151.37,562.6L153.22,564.81L153.08,564.17L154.71,563.62L156.17,565.17L156.17,565.17L155.03,568.79L153.76,569L153.67,571.2L152.83,571.61L152.69,571.21L151.74,571.47L151.94,572.01L152.7,571.8L152.81,572.08L154.28,570.97L154.66,572.2L154.31,572.35L154.51,573.39L154.19,573.61L154.77,575.12L155.55,574.72L156,576.06L155.87,579.27L157.52,579.41L158.77,579.98L159.18,580.71L159.22,582.57L156.55,583.19L156.31,582.29L155.68,584.21L156.5,583.87L157.58,585.55L157.04,586.13L157.53,586.21L158.66,587.41L160.47,591.73L161.56,595.4L163.54,596.82L161.26,598.98L161.02,599.92L162.22,600.28L163.35,599.92L163.55,600.55L162.63,600.86L162.99,602.69L162.03,602.93L162.31,604.07L161.71,604.31L162.07,605.83L161.52,605.55L161.83,606.43L161.44,606.61L161.11,606.33L160.94,607.1L161.27,608.08L160.87,608.59L159.85,608.28L159.28,607.64L159.63,608.61L160.03,608.41L160.36,608.67L159.45,608.88L159.29,609.51L158.46,610.26L157.89,608.75L157.55,608.81L157.72,608.34L157.05,608.85L156.79,608.31L155.39,608.82L155.55,609.41L155.18,609.68L155.85,610.89L155.1,612L151.26,609.65L147.96,614.27L148.04,614.73L145.25,617.82L145.25,617.82L145.25,617.82L145.25,617.82L144.59,616.85L142.37,615.96L141.68,612.99L141.98,611.4L141.57,609.53L140.61,609.46L140.57,611.18L139.7,611.22L139.51,608.85L138.55,609.97L138.93,610.75L138.85,611.6L138.09,610.87L134.09,614.71L128.96,614.38L129.41,617.53L128.04,616.52L127.11,616.97L126.36,616.78L125.28,616.03L124.86,615.18L124.55,615.52L124.3,615.34L124.68,614.98L124.2,614.5L123.88,614.79L123.53,614.54L123.57,613.61L121.65,614.74L120.87,616.91L121.3,617.32L121.29,618.06L120.45,618.17L120.23,618.59L119.85,618.4L120.08,619.09L119.53,619.96L109.6,624.23L107.46,624.15L107.46,624.15L107.46,624.15L107.46,624.15L104.84,624.01L99.78,621.46L97.61,628.26L97.02,628.1L95.15,629.09L91.3,635.49L87.21,635.7L84.39,640.46L80.08,643.96L71.57,641.18z"},{id:"FI-04",title:"Southern Savonia",d:"M231.13,612.1L231.34,613.43L230.55,615.01L233.49,618.37L230.11,619.27L230.25,620.09L229.98,620.36L230.54,621.62L228.24,622.51L228.95,623.34L228.75,624.42L229.2,626.2L229.79,626.77L229.56,627.85L228.88,628.16L228.41,627.82L228.16,626.77L227.85,627.03L227.63,626.81L226.15,624.5L225.44,625.19L225.16,625.03L225.25,625.61L224.07,625.79L224.61,627L223.77,627.77L223.45,627.57L223.11,628.29L222.77,628.2L222.79,627.51L222.47,627.2L222.02,627.73L222.01,628.44L220.49,628.51L219.36,629.47L218.86,628.97L215.89,634.51L222.04,644.45L219.73,645.79L219.44,647.13L219.71,649.38L219.16,650.82L220.03,650.43L220.86,650.58L220.69,651.45L221.22,652.59L220.9,653.06L220.9,655.28L220.53,655.71L222.44,656.53L225.14,661.16L225.85,663.49L225.55,665.34L225.31,665.32L225.28,666.74L225.54,666.67L225.28,667.89L220.79,665.74L220.61,666.93L219.95,667.3L220.07,668.25L218.87,669.08L218.87,669.08L218.97,671.44L218.5,671.08L217.15,671L217.91,671.81L217.86,672.86L218.03,673.36L218.37,673.41L218.15,674.7L217.39,674.9L217.64,675.9L218.72,676L219,674.8L219.21,675.78L219.69,675.64L219.93,676.11L217.22,675.98L218.14,678.55L216.54,679.89L217.24,681.28L218.99,683.14L217.86,684.82L217.95,685.2L218.96,684.99L218.96,685.85L221.62,688.23L221.62,688.23L221.87,688L223.71,688.17L223.71,688.17L224.13,688.24L224.6,689.23L225.08,691.59L225.08,691.59L226.1,691.24L226.68,691.67L228.91,690.33L230.15,693.49L228.89,694.99L229.88,695.94L232.56,694.38L233.49,691.88L236.9,690.74L237.27,693.56L238.22,694.64L238.53,695.68L238.03,697.48L241.98,699.59L244.09,699.32L244.82,698.75L245.44,699.04L247.37,698.9L247.37,698.9L249.47,698.65L250.5,697.96L250.93,698.48L252.13,698.22L252.39,697.84L252.3,696.8L253.2,696.33L253.13,695.65L252.32,695.82L251.25,694.88L251.2,693.88L251.96,693.33L250.67,691.57L250.13,689.77L249.85,689.97L248.36,689.34L247.85,688.67L249.14,688.73L249.21,688.14L247.64,687.67L246.32,688.08L245.46,687.88L245.34,688.59L243.45,687.63L241.93,686.36L240.52,686.8L239.38,686.64L239.59,685.99L240.79,685.33L241.47,684.03L243.15,684.38L243.73,685.12L244.23,685.2L245.18,685.04L246.08,683.02L249.3,682.82L249.88,683.18L250.52,682.88L252.5,683.24L254.61,684.28L255.74,684.34L257.42,685.29L258.43,685.48L259.07,686.1L262.24,686.08L264.77,685.13L268.05,686.38L270.43,686.44L274.59,686.13L280.84,684.48L281.27,684.67L281.13,684.16L281.9,683.72L282.63,682.02L283.67,682.04L283.76,681L286.41,679.29L286.21,677.32L286.89,675.6L287.57,676.39L288.45,675.48L289.54,676.5L289.54,677.8L291.29,677.88L291.77,678.46L293.45,678.16L293.58,678.71L295.69,677.55L298.13,677.85L298.16,676.75L298.79,676.2L298.95,673.94L301.15,674.54L303.37,673.69L306.28,674.11L311.67,672.43L313.04,672.54L313.94,670.16L317.52,666.25L322,664.05L322.63,661.51L322.63,661.51L323.01,660.54L325.16,658.81L326.36,656.72L326.8,654.69L326.72,653.68L326.02,652.57L326.95,651.87L324.4,648.54L324.43,647.02L325.84,644.26L322.88,641.03L322.98,640.61L320.97,640L319.42,637.14L317.79,629.03L318.47,626.55L317.25,625.43L314.68,620.02L314.15,616.11L313.3,614.74L312.09,614.04L311.09,615.14L310.34,614.67L309.84,615.37L310.03,616.18L308.29,615.72L307.76,615.03L308.12,614.27L307.31,613.5L308.31,608.94L307.25,608.83L305.9,607.73L304.81,607.44L305.87,606.99L305.7,606.2L304.93,605.87L302.83,603.8L302.89,602.99L300.31,601.37L297.99,598.57L294.34,597.96L293.66,597.38L293.66,597.38L292.97,599.91L291.86,600.65L292.73,600.97L292.02,602.19L291.21,602.73L290.64,601.6L289.87,602.44L287.83,602.35L290.11,603.56L289.37,604.94L287.9,603.7L287.64,603.86L286.97,603.39L285.57,603.14L285.92,603.63L285.45,604.47L285.78,605.97L285.08,607.71L284.72,607.61L284.48,608.11L285.26,609.33L284.96,610.95L284.16,611.02L283.13,610.23L282.5,610.38L282.01,610L281.58,610.82L282.27,611.52L282.22,612.29L280.78,612.98L280.57,613.56L281.78,614.29L281.82,615.7L283.29,616.77L282.94,617.4L283.05,618.06L284.82,618.3L285.28,619.82L285.13,621.8L285.73,622.1L288.62,620.43L293.49,626.51L293.49,628.03L291.96,630.16L289.99,630.16L285.73,628.18L283.91,627.88L281.78,626.66L279.04,627.27L275.4,627.27L271.76,624.74L271.63,625.15L269.33,622.83L269.38,623.61L268.21,623.12L267.69,623.71L267.36,623.57L265.91,621.31L264.39,620.48L264.24,619.31L265.36,618.01L265.06,617.54L262.91,617.03L262.65,616.07L261.67,615.32L260.93,613.96L259,611.87L255.67,610.36L255.44,609.52L254.11,608.69L253.86,608.11L253.17,608.01L252.39,606.3L251.84,606.81L252.63,607.3L252.46,607.86L251.96,607.81L252.26,608.59L251.59,608.58L250.48,609.36L249.92,610.98L249.36,610.9L248.81,609.79L248.07,609.74L247.79,610.9L247.41,611.03L247.29,610.71L247.71,610.17L247.49,609.91L246.87,610.46L247.01,611.42L246.17,611.22L246.36,610.82L246.04,609.63L244.43,607.94L244.58,608.47L244.18,608.7L244.06,609.41L243.33,609.22L242.71,610.38L240.64,610.47L239.67,609.21L239.11,609.96L239.84,611.27L239.32,612.33L238.73,611.34L237.15,610.03L236.93,609.37L235.43,610.6L234.92,611.45L235.43,612.37L233.2,613.63L231.48,611.63z"},{id:"FI-05",title:"Kainuu",d:"M236.57,499.24L233.68,497.69L233.31,482.62L231.57,482.32L230.76,481.73L230.8,479.15L230.51,478.77L226.46,478.4L223.64,475.9L223.51,475.12L224.15,474.36L223.66,473.79L224.02,473.89L223.78,473.28L224.18,473.41L224.2,472.52L223.53,472.75L222.45,470.38L218.18,466.66L219.34,465.26L219.03,464.71L219.86,464.55L219.66,463.88L220.3,464.19L223.56,460.31L226.33,460.77L225.84,459.55L226.6,459.2L227.31,459.92L227.24,458.51L228.03,456.8L229.71,455.73L229.64,454.74L229.07,454.21L229.65,453.66L229.97,454.09L230.82,453.9L230.15,454.56L230.95,455.57L231.24,455.33L230.75,454.99L231.52,454.56L231.44,454.28L232.19,453.94L232.45,454.37L235.64,453.06L236.29,450.98L237.16,451.31L237.07,450.41L237.6,450.26L237.29,449.8L237.34,448.72L237.67,448.65L237.82,448.07L237.34,447.58L237.88,445.76L245.47,440.08L246.67,440.34L247.28,440.85L247.61,440.64L252.11,441.86L252.82,440.44L252.36,439.56L253.36,439.29L253.66,438.61L252.62,435.98L253.72,433.23L253.58,432.59L252.92,432.13L253.42,431.76L253.15,430.84L251.53,428.69L251.1,428.56L249.21,425.6L251.33,420.81L255.28,421.09L259.03,420.57L260.09,419.58L262.16,418.5L265.66,419.64L266.14,418.8L266.01,419.71L269.39,420.8L270.71,414.82L271.02,414.95L270.8,414.42L271.6,414.94L270.98,414.51L271.58,413.96L271.49,413.67L270.87,414.08L271.12,412.2L273.87,409.6L281.24,407.97L281.68,408.44L281.98,407.86L287.8,406.77L288.2,406.03L288.56,406.18L288.08,406.72L288.92,407.37L288.45,406.66L291.66,406.06L292.32,404.27L292.12,403.94L292.89,400.75L293.75,399.37L293.48,398.03L298.5,395.83L297.64,395.62L298.16,395.51L298.16,395.11L298.5,395.06L298.67,395.72L303.39,393.61L306.15,394.39L309.44,393.43L308.66,393.39L309.56,392.46L310.49,392.69L309.68,392.3L310.64,391.3L310.89,391.57L310.96,390.91L311.78,390.07L311.63,388.15L314.99,387.95L320.8,390.41L321.52,390.16L321.5,389.65L322.38,389.14L327.49,390.08L328.88,389.79L328.88,389.79L328.67,390.96L328.17,391.69L328.04,395.21L328.14,399.31L328.59,401.28L325.42,405.68L324.21,406.76L323.97,407.91L325.02,410.15L328.49,410.56L329.22,410.34L331.86,411.21L333.05,412.07L333.29,413.07L330.95,416.84L331.92,417.99L332.35,417.65L332.04,418.14L333.38,419.77L332.66,419.87L331.31,420.76L328.21,420.81L324.77,423.2L324.39,426.78L323.91,428.14L324.51,430.83L324.24,433.31L325.2,437.17L325.41,437.89L327.11,440.01L326.75,441.39L328.37,443.53L338.07,443.29L339.46,444.7L339.61,445.38L338.05,447.21L338.47,449.35L341.07,454.1L340.93,455.06L340.51,455.84L338.52,456.61L336.45,458.71L336.71,459.54L336.37,462.68L337.23,464.87L337.69,465.16L337.57,466.47L338.25,467.31L338.61,468.82L338.23,472.46L340.27,475.18L341.23,475.73L343.57,476.28L348.48,480L348.31,481.37L349.17,482.24L352.21,482.78L353.06,485.73L351.68,487.05L353.24,490.57L354.48,492.33L354.48,494.53L353.64,498.41L351.1,503.12L347.01,508.52L345.03,514.89L341.39,516.47L335.86,519.56L335.86,519.56L332.69,520.16L329.57,523.41L327.86,520.27L326.52,510.77L313.76,512.8L301.1,513.87L289.21,510.59L287.35,511.38L287.86,512.33L284.25,519.64L284.25,519.64L284.25,519.64L284.25,519.64L281.5,525.84L279.47,523.14L277.34,521.8L274.68,517.75L270.01,512.76L269.31,512.87L264.61,508.6L262.05,507.51L261.54,507.78L258.04,505.04L256.14,504.75L256.62,505.53L255.11,505.91L254.06,505.05L254.3,504.54L254.09,504.35L248.98,502.6L245.02,502.07L244.61,502.51L241.31,501.96z"},{id:"FI-06",title:"Tavastia Proper",d:"M173.98,688.13L174.38,690.9L175.21,690.44L175.87,691.44L177.22,690.42L177.75,693.25L180.22,692.71L183.27,693.68L183.22,694.85L184.39,696.37L184.99,696.63L185.16,697.24L184.86,697.92L185.46,699.2L184.42,700.23L185.1,701.08L183.74,702.63L183.17,704.51L182.22,704.69L181.67,705.38L178.67,706.27L177.67,707.54L178.3,708.29L177.69,709.82L178.57,709.71L178.43,710.21L178.72,710.38L177.61,712.13L177.09,714.26L178.33,714.34L179.83,714.94L180.32,718.47L179.73,718.52L179.33,720.06L179.74,721.18L180.19,721.21L180.31,721.7L180.31,721.7L180.18,722.1L181.77,724.05L181.72,724.69L179.74,725.1L178.72,727.53L178.96,728.25L180.64,726.18L181.49,727.15L182.98,727.63L179.56,729.32L180.36,731.73L178.79,731.26L177.93,730.22L174.73,730.94L174.23,731.64L173.49,731.62L173.38,731.9L171.46,731.9L171.43,731.43L170.7,731.12L170.26,732.17L169.32,731.9L168.46,732.65L166.92,732.53L164.47,731.37L162.94,733.36L162.83,735.66L163.24,736.67L162.35,738.36L158.41,738.81L157.6,737.14L157.93,736.23L156,734.98L154.26,736.75L154.57,737.65L153.98,737.95L152.36,735.78L152.42,734.59L150.49,733.94L149.13,734.24L147.58,733.92L146.18,732.87L143.89,733.27L142.25,732.24L141.62,732.5L141.62,732.5L138.86,732.11L136.73,732.35L135.73,731.62L134.72,732L134.41,731.13L134.61,730.33L132.77,729.62L131.2,729.56L130.18,729.01L129.76,728.05L128.88,727.44L128.89,726.33L128.41,726.13L126.96,726.11L123.52,728.04L121.83,727.53L121.65,728.36L120.69,727.06L118.31,724.98L117.82,724.34L119.23,721.58L120.16,721.03L117.37,720.12L117.28,717.15L117.9,716.64L121.35,716.86L120.91,714.86L122.07,715.04L122.43,713.74L122.12,713.39L122.27,712.59L120.97,711.96L119.24,709.51L119.24,709.51L119.79,709.11L121.37,709.18L121.21,708.32L121.21,708.32L123.54,708.96L124.43,708.72L125.94,711.66L127.02,711.5L127.95,712.05L127.37,710.82L128.07,710.23L129.02,709.98L129.94,710.33L130.27,709.66L130.9,709.9L131.03,709.57L131.64,709.91L131.2,710.2L131.58,710.64L132.31,710.15L132.66,709.42L132.66,709.42L134.84,709.32L134.84,709.32L135.69,708.97L136.44,709.51L136.44,709.51L136.44,709.51L136.44,709.51L136.42,710.15L136.42,710.15L136.42,710.15L136.42,710.15L137.36,709.86L138.26,710.38L139.71,713.58L140.5,712.61L140.1,710.98L138.97,709.59L139.52,709.44L139.55,708.85L139.89,709.05L140.93,708.16L140.51,707.2L138.21,707.95L138.49,706.33L137.08,705.83L138.55,704.42L139.19,704.22L139.9,704.71L141.36,704.13L145.83,701.42L146.82,701.74L148.33,701.19L149.42,701.52L149.15,700.64L149.34,700.15L152.33,699.69L154.54,696.92L153.48,695.8L153.16,694.97L153.9,693.74L154.72,694.17L157.27,693.13L157.62,693.3L157.78,692.79L158.31,692.85L159.17,691.78L159.51,691.92L160.64,690.9L163.18,689.48L163.72,690.45L166,691.23L166.82,691.11L167.44,691.64L168.25,688.59L169.42,691.82L170.66,691.56L173.19,690.62L172.91,689.94z"},{id:"FI-07",title:"Central Ostrobothnia",d:"M131.93,488.17l0.17,-0.5l0.49,0.18l0.59,-0.91l0.47,-0.07l1.11,2.3l-0.52,-0.29l-0.37,-0.84l-0.23,0.35l-0.37,-0.4l-0.15,0.55l-0.67,-0.11l-0.08,0.26L131.93,488.17zM106.16,507.75l0.46,0.72l0.15,-0.33l0.34,0.14l0.01,-0.62l-0.51,-0.25L106.16,507.75zM110.95,514.3l0.92,-0.2l-0.43,-0.33l0.27,-0.14l-0.25,-0.61l0.37,-0.32l-0.7,-1.07l0.82,0.27l-0.31,-0.9l-0.4,0.26l0.05,-0.49l-0.33,-0.01l0.09,-1.04l-0.69,0.14l-0.01,-0.3l-0.78,-0.18l-1.36,0.26l-0.29,-0.8l-0.36,-0.07l-0.35,0.47l0.45,0.44l-0.72,0.37l0.48,0.08l0.13,1.1l1.53,0.65l0.53,-0.23l0.42,0.69l0.02,0.33l-0.76,-0.07l0.39,1.23l-0.82,0.07l0,-0.36l0.33,0.04l-0.5,-0.4l0.05,1.08l0,0l0.5,1.15l-0.27,0.68l0,0l0.16,-0.32l-0.04,0.88l1.29,1.44l0,0l0.33,0.57l-0.05,-0.65l1.87,-0.38l0.02,-0.4l0,0l0.16,-1.34l-0.21,-0.74l-0.34,-0.04L110.95,514.3zM135.04,489.97l-0.54,0.12l0.07,0.59l-0.76,0.84l-0.05,0.57l-0.68,-0.68l0.46,0.74l-0.35,0.56l0.28,0.66l-0.53,0.11l-0.71,-0.8l-0.42,0.09l-0.24,0.54l0.54,1.13l-0.23,0.84l-0.25,-0.06l0.58,0.53l-0.05,-0.76l0.98,1.48l-0.49,1.24l0.13,0.91l-0.58,0.17l-0.37,-0.96l-0.22,0.08l0.33,0.63l-0.75,0.35l-1.91,-0.82l-0.12,-0.59l-0.22,0.5l-0.77,-0.12l-1.06,-1.35l-0.09,-0.6l-1.1,0.18l-0.26,-0.24l0.19,0.85l-0.58,0.49l-0.17,0.83l0.36,3.14l-0.52,0.6l0.45,0.17l0.14,0.6l-0.64,0.04l0.76,0.76l-0.31,0.59l-0.79,0.2l1.07,1l0.38,1.06l-0.82,0.56l-0.17,-0.21l-0.32,0.48l0.56,0.46l-0.3,0.31l-0.49,-0.38l0.33,0.73l-0.55,0.02l-0.37,-0.88l-1.11,-1.04l-0.17,1.05l0.68,0.41l-1,0.36l-0.16,0.37l-0.65,-0.68l-0.8,0.33l0.22,0.5l-1.32,-0.66l0.39,0.55l-0.42,-0.07l0.13,0.78l-0.73,-0.99l-0.77,-0.04l-0.29,0.66l-0.83,-1l0.28,0.52l-0.41,-0.06l0.9,1.55l-0.3,0.33l-0.24,-0.28l-0.17,0.4l-0.78,-0.84l-0.4,-1.19l-0.62,-0.33l0.04,0.87l0.48,0.18l1.28,2.13l-0.4,1.25l-0.58,0.08l0.14,-0.91l-0.41,-0.27l-0.12,-0.68l-0.49,-0.25l-0.17,0.69l-0.84,-0.18l-0.4,0.87l0.35,0.28l-0.26,0.58l-0.52,-0.09l0.16,0.87l0.74,0.62l-0.54,0.86l-0.4,-0.58l-0.41,0.36l0.37,0.75l0.4,0.09l-0.67,1.17l0.49,-0.09l-0.14,0.54l0,0l6.84,5.26l0.27,0.55l0.32,-0.18l0.55,-2.11l1.93,-1.47l1.18,0.46l0.35,-0.15l-0.32,-0.01l0.22,-0.25l0.63,0.17l0.41,0.63l0.49,-0.17l0.92,1.12l0.28,-0.3l0.01,-1.61l0.65,-1.08l8.39,7.37l-1.11,1.43l-1.77,-0.97l-1.21,1.42l-2.05,1.21l-0.77,-0.19l-0.6,-0.78l-0.05,-1.74l-0.51,0.84l-0.59,-0.06l0.5,1.45l-1.01,0.8l0.42,0.64l-0.22,0.59l-0.66,-0.57l-0.51,0.19l2.18,2.22l0.57,-0.57l0.64,0.26l0.79,-1.08l0.83,1.46l-0.72,0.8l0,0.44l0.75,-0.14l-0.13,0.49l0.37,0.3l-0.25,0.41l2.2,1.58l0.23,4.95l0.34,0.74l-0.24,0.11l0.02,1.11l1.57,3.72l-0.36,0.23l0,0l2.24,4.75l2.81,2.54l3.13,0.12l2.03,0.58l2.54,1.64l2.26,2.2l2.17,3.02l-0.73,0.63l-0.11,-0.61l-0.62,0.42l0.04,0.38l-0.44,-0.1l-0.32,0.95l1.2,-0.5l1.86,2.21l-0.15,-0.65l1.63,-0.54l1.46,1.55l0,0l5.7,-2.76l7.77,1.65l-1.31,-0.95l0.46,-3.54l0.52,-1.49l-0.34,-2.4l0.46,-0.25l-0.39,-0.75l1.58,-0.74l-0.97,-5.87l4.23,-5.23l4.07,-1.84l0,0l-6.95,-9.28l-2.11,-1.82l-4.22,-2.67l-1.88,-2.9l-4.31,-10.71l-4.51,-1.72l-1.16,-1.03l-0.91,-2.85l-0.07,-1.27l-1.31,-0.49l-2.46,-4.77l-0.45,-4.76l-2.61,-1.55l-1.86,-0.42l0.16,-0.58l-2.24,-1.02l-0.14,-0.49l-0.1,0.23l-0.53,-0.24l-0.19,0.4l-1.39,-1.11l-0.7,0.89l0.12,-1.49l-0.72,-0.36l-0.21,-0.51l-0.54,0.01l-1.45,-1.04l0,0l-0.26,0.34L135.04,489.97z"},{id:"FI-08",title:"Central Finland",d:"M208.74,543.07L205.49,542.3L202.77,538.43L201.38,537.45L199.28,536.58L194.06,536.28L192.41,535.67L184.87,529.91L181.34,532.66L180.44,537.95L179.47,540.31L177.97,540.99L177.97,540.99L173.9,542.82L169.67,548.05L170.63,553.92L169.05,554.66L169.44,555.41L168.97,555.66L169.31,558.07L168.79,559.56L168.33,563.1L169.65,564.06L161.88,562.41L156.17,565.17L156.17,565.17L155.03,568.79L153.76,569L153.67,571.2L152.83,571.61L152.69,571.21L151.74,571.47L151.94,572.01L152.7,571.8L152.81,572.08L154.28,570.97L154.66,572.2L154.31,572.35L154.51,573.39L154.19,573.61L154.77,575.12L155.55,574.72L156,576.06L155.87,579.27L157.52,579.41L158.77,579.98L159.18,580.71L159.22,582.57L156.55,583.19L156.31,582.29L155.68,584.21L156.5,583.87L157.58,585.55L157.04,586.13L157.53,586.21L158.66,587.41L160.47,591.73L161.56,595.4L163.54,596.82L161.26,598.98L161.02,599.92L162.22,600.28L163.35,599.92L163.55,600.55L162.63,600.86L162.99,602.69L162.03,602.93L162.31,604.07L161.71,604.31L162.07,605.83L161.52,605.55L161.83,606.43L161.44,606.61L161.11,606.33L160.94,607.1L161.27,608.08L160.87,608.59L159.85,608.28L159.28,607.64L159.63,608.61L160.03,608.41L160.36,608.67L159.45,608.88L159.29,609.51L158.46,610.26L157.89,608.75L157.55,608.81L157.72,608.34L157.05,608.85L156.79,608.31L155.39,608.82L155.55,609.41L155.18,609.68L155.85,610.89L155.1,612L151.26,609.65L147.96,614.27L148.04,614.73L145.25,617.82L145.25,617.82L145.61,621.09L146.39,622.31L146.96,622.12L147.29,622.44L147.47,623.84L149.78,625.43L152.94,625.42L153.37,624.95L154.24,629.27L155.65,631.24L157.3,631.35L157.41,630.92L157.69,630.94L157.66,631.51L157.87,631.59L157.98,631.07L158.51,632.28L158.95,631.93L158.75,630.74L160.85,629.25L160.96,628.79L162.71,629.98L164.07,633.16L164.77,633.97L166.38,634.8L166.18,639.11L167.36,639.53L168.23,641.08L167.08,643.23L163.73,644.9L163.13,646.88L163.28,648.4L166.93,653.11L171.18,657.52L170.42,658.43L169.05,659.04L169.05,661.62L169.66,663.29L171.18,663.29L172.4,663.75L172.55,664.81L172.11,666.54L172.11,666.54L172.63,666.7L171.4,666.32L171.4,666.32L170.79,665.64L169.89,668.22L170.19,669.29L171,670.26L171.55,672.57L171.96,670.49L173.26,669.83L174.14,670.43L174.1,671.94L172.89,673.32L175.04,673.77L174.39,675.99L174.54,677.66L175.9,679.69L175.9,679.69L179.31,678.55L179.19,677.91L179.77,678.26L180.63,678.18L181.43,679.02L182.72,677.77L184.92,678.13L185.6,677.66L190.75,677.19L192.99,667.54L192.79,664.52L193.87,664.3L194.93,664.72L196.27,664.25L198.13,661.81L198.76,661.72L200.78,662.63L201.05,663L200.61,663.51L201.44,663.94L203.49,658.15L204.16,657.58L203.91,656.14L205.03,656.59L204.32,658.78L205.81,658.52L206.3,656.95L206.47,657.48L208.25,658.94L208.56,660.86L209.25,661.49L210.22,661.27L210.48,660.34L210.9,661.12L210.81,661.83L211.38,662.29L211.28,665.04L213.37,668.23L214.22,668.38L214.93,666.33L216.07,666.91L217.32,666.86L217.86,665.87L218.06,666.32L218.4,666.07L218.82,667.02L218.41,667.89L218.87,669.08L218.87,669.08L220.07,668.25L219.95,667.3L220.61,666.93L220.79,665.74L225.28,667.89L225.54,666.67L225.28,666.74L225.31,665.32L225.55,665.34L225.85,663.49L225.14,661.16L222.44,656.53L220.53,655.71L220.9,655.28L220.9,653.06L221.22,652.59L220.69,651.45L220.86,650.58L220.03,650.43L219.16,650.82L219.71,649.38L219.44,647.13L219.73,645.79L222.04,644.45L215.89,634.51L218.86,628.97L219.36,629.47L220.49,628.51L222.01,628.44L222.02,627.73L222.47,627.2L222.79,627.51L222.77,628.2L223.11,628.29L223.45,627.57L223.77,627.77L224.61,627L224.07,625.79L225.25,625.61L225.16,625.03L225.44,625.19L226.15,624.5L227.63,626.81L227.85,627.03L228.16,626.77L228.41,627.82L228.88,628.16L229.56,627.85L229.79,626.77L229.2,626.2L228.75,624.42L228.95,623.34L228.24,622.51L230.54,621.62L229.98,620.36L230.25,620.09L230.11,619.27L233.49,618.37L230.55,615.01L231.34,613.43L231.13,612.1L231.48,611.63L231.48,611.63L230.7,610.93L229.05,611.74L223.9,607.04L224.23,606.08L225.08,606.07L225.69,605.42L226.67,603.78L227.11,602.26L227.99,602.11L227.28,601.17L227.97,600.58L227.7,598.6L227,597.67L226.88,595.61L225.76,593.87L225,591.45L223.93,589.54L223.02,588.29L221.35,589.21L221.61,589.93L220.21,591.19L215.96,585.74L215.51,585.36L214.83,585.73L213.77,584.29L214.7,583.41L214.69,582.95L211.02,581.21L210.14,578.15L211.52,577.79L212.81,576.84L216.06,576.65L217.58,578.65L219.46,574.62L218.14,574.69L215.96,571.62L216.48,570.36L219.55,570.95L219.4,570.42L216.66,568.41L215.89,567.2L215.4,565.53L214.89,565.04L214.92,564.05L214.16,563.16L213.6,558.73L214.75,558.46L214.52,556.57L213.43,554.03L213.02,550.13L211.63,548.46L211.17,548.35L212.74,544.74L214.5,542.37L213.3,541.04z"},{id:"FI-09",title:"Kymenlaakso",d:"M225.08,691.59l1.01,-0.35l0.58,0.43l2.23,-1.34l1.25,3.16l-1.27,1.5l0.99,0.95l2.68,-1.56l0.93,-2.5l3.41,-1.14l0.36,2.82l0.96,1.07l0.31,1.05l-0.51,1.8l3.96,2.11l2.1,-0.27l0.74,-0.58l0.62,0.3l1.93,-0.15l0,0l0.28,1.42l-1.23,2.31l0.35,0.4l0.47,-0.36l0.94,0.98l-1.6,0.32l-1.09,1.12l-0.07,1.36l0.41,1.31l-0.58,1.17l1,0.82l1.16,-0.67l0.43,2.01l0.81,0.72l-2.15,1.05l-0.86,-0.17l-0.7,-0.94l-0.28,0.26l0.44,0.78l2.54,3.11l4.99,1.61l2.58,3.8l1.68,1.45l1.36,0.08l2,-0.5l2.17,0.23l1.15,0.43l-0.12,0.48l0.72,1.78l1.28,0.15l0.63,-0.67l1.83,0.26l0.36,1.83l1.3,2.6l1.64,0.76l0.03,1.24l1.22,-0.14l0,0l-3.81,4.19l-1.1,1.68l0.17,1.16l-1.88,0.99l-0.57,-1.8l0.17,-0.39l-1.21,-0.24l-0.41,0.27l0.46,0.56l-0.59,0.3l0.24,0.94l-0.25,0.65l0.18,0.55l0.63,0.17l0.18,0.65l-0.5,0.75l0.42,0.3l-0.06,0.66l-0.3,0.19l-0.94,-0.36l-0.64,0.73l-1.62,-0.52l0.02,0.65l-0.45,0.04l-0.99,-0.63l0.27,0.67l0.79,0.51l-0.02,0.38l-1.36,-0.48l-0.42,-0.97l-2.04,-0.78l-0.26,-0.56l-0.22,0.62l-0.83,0.25l-0.06,0.41l0.34,0.69l0.51,0.07l0.2,1.24l-1.28,-0.91l-0.76,0.54l-0.52,-0.47l0.06,-0.65l-1.31,-1.43l-0.13,0.54l0.49,0.31l-0.16,0.3l-1.19,-0.14l-0.04,-0.31l0.66,-0.23l0.08,-0.38l-0.21,-0.3l-0.62,0.16l-0.82,-0.29l-0.18,-0.77l-0.87,0.97l-0.42,-0.79l-1,-0.4l-1.13,0.66l0.23,-1.11l-0.51,-0.79l0.16,-0.54l0.42,-0.04l2.1,1.77l0.26,-0.44l-1.91,-1.31l0.05,-0.39l-0.87,-0.3l-0.86,0.14l0.28,1.8l-0.36,0.96l-0.41,0.14l-0.72,-0.35l-0.76,-1.15l-0.51,0.58l-0.38,-0.38l-1.25,0.98l-0.66,-1.16l-0.01,-0.79l-0.56,-0.11l0.66,1.99l-0.56,0.8l-0.75,-0.29l0.29,1.2l-0.28,0.44l-0.28,-0.36l-0.14,0.49l0.63,1.53l-0.4,-0.18l-0.44,-1.28l-0.49,0.14l-0.13,0.43l0.7,0.4l-0.76,1.68l-1.44,-1.7l-0.33,0.16l0.43,1.33l0.61,0.17l-0.09,0.5l0.41,0.48l-0.34,0.45l-0.88,0.03l-0.13,-0.57l-0.72,-0.21l-0.07,0.43l-0.36,-0.09l-0.25,-1.03l0.98,-0.5l-0.01,-0.8l-0.6,-0.81l-0.32,0.76l-0.62,0.05l-0.88,0.73l-1.05,-1.06l0.11,-0.36l-1.12,-0.56l0.45,2.29l-0.76,-0.13l-0.41,1.28l-1.12,-0.14l0.04,0.63l-0.78,-0.39l-0.45,-1.56l-0.53,-0.31l-0.68,0.26l-0.56,-0.33l-0.3,0.52l-0.31,-0.13l0.17,1.7l-0.68,-0.57l-0.21,-0.78l-0.43,-0.21l-0.19,0.27l-1.16,-1.07l-0.46,-1.32l-0.48,-0.29l0,0l0.32,-0.34l0.11,-1.21l1.3,-0.84l-0.68,-1.12l0.65,-0.67l1.06,-0.07l0.17,-1.31l1.42,-2.12l2.01,-0.43l1.31,1.64l1.84,0.85l-0.28,-0.62l-1.98,-4.16l-1.18,-0.16l-1.5,0.59l-0.12,0.92l-0.9,1.35l-0.72,1.99l-0.15,-1.17l-1.8,-0.16l-0.06,-1.05l-0.92,-1.78l-0.75,-0.56l-2.62,-0.72l0.45,-0.45l-0.76,-0.54l-0.43,-1.27l0.16,-1.16l-0.96,-1.11l0.03,-1.17l-1,-0.85l-0.46,0.05l-0.07,0.8l-0.76,0.01l-0.63,-0.61l0,0l-0.3,-2.98l-2.47,-1.9l-0.84,0.18l-0.63,-0.45l0.48,-1.61l0.92,-0.62l-0.24,-0.86l0.32,-0.91l1.46,-2.1l-3.52,-0.56l-0.58,-2.3l0.2,-0.68l0.45,-0.11l-0.04,0.49l0.41,0.35l1.32,-0.88l0.52,-2.8l-0.46,-1.2l-0.47,-0.18l0.14,-1.89l-1.95,-1.25l1.85,-2.92l1.11,-0.97l0.37,1.18l2.72,0.42l1.02,-1.21l-0.01,-0.91l2.35,-0.55l1.39,-1.1l0.45,-1.8l0.97,-1.35l0.02,-1.1l0.57,-0.58L225.08,691.59z"},{id:"FI-10",title:"Lapland",d:"M178.49,380.6l-0.07,1.17l-0.7,-0.86l0.55,-0.54L178.49,380.6zM163.88,373.86l0.49,0.13l-0.71,1.36l0.42,1.34l-0.51,-0.2l-0.12,0.97l-1.27,-0.26l-0.04,0.33l-0.29,-0.39l-0.63,0.21l0.47,-0.6l-0.47,0.19l-0.02,-0.91l0.54,-0.22l0.66,0.22l0.6,-0.46l0.57,-0.85l0.09,-1.13L163.88,373.86zM271.76,1.51l0.65,5.95l5.65,8.66l5.88,3.66l-0.52,2.92l2.46,3.02l23.27,11.27l1.13,5.01l5.36,14.83l-3.84,7.44l-12.31,15.55l-0.04,4.64l-0.82,5.49l1.73,3.25l2.33,2.15l-13.71,10.68l-2.73,1.48l1.69,2.64l6.27,-0.06l4.33,1.5l-3.18,12.17l-8.67,16.75l7.02,29.93l21.58,10.33l2.22,4.87l0.5,0.26l-0.06,0.73l1.45,3.54l3.52,7.37l1.02,1.26l2.86,5.88l10.74,9.55l-3.01,13.2l-2.98,3.77l-4.07,7.36l-1.08,1.43l-0.59,0.14l-0.44,1.3l-0.67,0.23l-0.17,0.62l0.83,0.27l-0.04,0.41l-0.97,0.78l-0.92,-0.31l-0.18,0.56l-0.39,0.12l0.41,0.49L323,245l-1.48,0.12l-0.6,1.83l0.35,0.62l-14.17,23.45l-1.02,2.89l-0.21,2.81l0.86,5.72l1.82,4.08l-0.33,1.11l1.44,0.94l6.65,11.39l-0.01,1.21l0.79,1.26l-0.25,0.4l1.29,0.87l-0.2,0.66l1.94,3.25l3.18,8.81l0,0l-10.01,0.06l-0.1,1.9l-17.9,-6.21l-0.95,5.8l-2.01,0.31l-0.41,-0.35l0.22,1.15l-0.45,-0.01l-0.29,1.44l-0.8,-0.02l0.13,2.99l-0.45,1.04l1.66,5.03l0.39,0.28l1.15,-0.13l0.17,1.13l0.53,0.32l0.75,-1.11l1.99,0.5l-0.19,0.67l0.55,0.7l-0.07,0.95l-0.64,0.49l0.41,0.4l-0.43,0.73l1.05,1.69l-1.66,1.88l-0.08,1.97l-0.86,0.68l-2.59,-0.02l0.63,2.87l0.55,0.41l-0.43,1.12l2.06,0.76l0.29,0.66l0.49,0.08l0.04,0.65l0.76,-0.53l0.6,0.54l-0.97,0.82l0.51,0.74l-0.07,1.72l-2.28,0.13l-0.71,1.04l-1.72,-0.07l-0.05,-0.92l-1.62,-0.74l-0.08,0.42l-1.9,0.03l-0.07,1.04l-2.19,0.24l-0.02,-0.92l0.64,-0.73l-1.93,0.46l0.53,0.46l0.02,1.15l0.29,0.13l-0.22,0.85l-0.55,-0.19l-0.19,0.24l0.11,0.6l1.92,1.11l0.85,2.22l1.53,2.1l0.2,3.5l-1.57,0.1l-7.68,3.41l-1.88,-0.48l-0.63,-0.56l-7.43,-0.55l-0.2,-0.59l-0.39,0.05l0.36,0.22l-0.12,0.3l-4.42,-0.33l0.17,-0.79l0.84,0.16l0.36,-1.09l-0.33,0.02l-0.35,0.79l-0.59,-0.22l-2.34,-4.62l-1.27,-4.64l-1.8,0.44l-1.08,2.02l-0.78,0.27l-3.02,-2.87l-1.04,1.54l0.24,0.44l-0.49,-0.08l-4.86,7.45l-0.54,0.05l0.2,0.44l-0.36,0.56l-0.18,-0.18l-0.03,0.49l-1.95,3.07l0.39,0.51l-0.44,0.22l-0.21,-0.33l-1.45,2.24l-0.59,0.28l0.25,0.48l-0.86,0.9l-1.2,-0.66l-0.9,0.42l-0.01,0.81l0.43,0.03l0.01,0.63l-1.17,0.09l-0.14,-1.18l-4.38,2.01l-4.99,-0.27l-0.08,-0.24l-0.19,0.71l-0.64,-0.77l-8.77,-0.29l-7.13,-0.87l-0.04,-7.56l-11.71,6.31l-11.85,-0.15l-2,1.14l-1.65,3.25l-2.52,1.36l-1,1.16l-0.24,-0.12l-1.95,3.7l-1.45,1.47l0,0l-0.07,-1.05l-0.67,-0.62l-0.19,-0.84l-1.93,-0.6l-0.05,-0.46l-0.94,0.03l0.1,0.19l-1.17,-0.21l-1.01,-0.84l0.14,-0.9l-0.35,-0.39l0.24,-0.53l-0.65,0.29l-0.36,-0.39l-0.46,0.5l-0.26,-0.46l-0.3,0.74l-0.52,-0.24l0.19,-0.35l-0.53,0.02l-0.22,-0.34l0.26,0.84l-0.67,0.92l-0.39,-0.95l-0.77,-0.5l-1.61,2.97l-0.86,-0.73l-0.6,-0.04l-0.03,-1.14l0.45,0.1l0.14,-0.51l-1.02,-1.29l0.11,-0.38l-0.61,-0.08l-0.67,-0.92l0.45,-0.62l0.78,1.31l-0.12,-1.54l-0.8,-0.68l-0.33,0.05l0.08,0.32l-0.39,-0.16l-0.75,-1.38l-0.55,0.29l-0.08,-1.35l-0.89,-0.11l0.04,-1.14l-0.25,1.35l-0.35,0.03l0.19,-1.8l-0.37,1.57l-1.54,-0.67l0.02,-0.6l0.73,-0.2l0.75,-1.01l-0.13,-0.46l-1.2,0.59l-0.72,-0.04l0.4,-1.22l-0.52,1.3l-0.46,0.16l-0.96,-0.84l-0.52,0.19l-0.36,-0.44l-0.05,0.3l-0.48,-0.72l-0.6,-0.17l-0.52,-1.25l0.03,1.16l-0.34,0.09l-1.25,-1.46l-0.63,-1.65l0.4,1.6l-0.77,-1.03l-0.68,-0.21l0.85,0.98l-0.09,0.97l-0.4,-0.16l0.27,0.32l-0.14,1.5l-0.79,-0.07l1.06,0.65l-0.24,0.75l-1.14,-1.03l0.17,1.03l-0.55,0.21l-0.35,-0.23l0.3,0.97l-0.32,-0.35l-0.02,0.3l-0.37,0.02l-0.41,-2.04l0.47,-0.02l0.37,-1.58l-0.88,-3.39l-0.5,-0.69l0.19,-0.89l0.54,-0.18l-1.11,-2.6l0.06,-2.25l-0.96,-0.38l-1.46,-2.41l-0.06,-0.5l0.37,-0.35l-0.13,-1.96l-2.77,-5.48l-0.67,-0.57l0.04,-3.57l-0.69,-1.25l0.27,-1.47l-1.13,-0.85l-0.7,0.09l-0.4,-0.47l-0.76,0.13l-1.45,-1.35l-1.9,-0.62l0.16,-0.93l-1,-1.08l-0.29,-0.86l0.17,-1.07l-0.87,-1.13l0.05,-1.05l-0.69,-2.47l0.31,-3.98l0.87,-2.73l-0.72,-0.96l-0.81,-2.44l0.31,-2.1l2.17,-1.67l-0.15,-1.16l0.52,-1.51l0.57,0.34l1.47,-0.98l-0.28,-1.52l2.25,-1.69l0.59,-1.46l0.35,-3.14l-0.46,-1.17l-0.16,-2.02l0.68,-1.48l0.28,-3l0.38,-0.81l-0.99,-2.71l0.13,-0.78l0.41,-0.5l0.75,-0.2l-0.06,-1.93l0.51,0.05l1.04,0.97l0.58,-0.16l-0.14,-0.94l0.38,-0.51l0.21,-1.52l-1.85,-4.97l-0.7,-0.44l-0.39,-1l-1.2,-1.46l-0.14,-2.93l-1.02,-0.51l-0.39,-1.57l-0.5,-0.24l-0.23,-0.88l-0.96,-0.69l-0.76,-1.24l-0.86,-2.15l-1.29,-1.77l-0.57,-3.1l-3.29,-5.52l0.42,-1.18l0.72,-0.46l0.24,-1.52l-1.54,-1.4l0.47,-0.89l-0.29,-0.96l0.55,-0.35l-0.2,-0.82l1.35,-0.95l0.51,0.17l1.88,-0.92l1.25,-0.06l0.55,-0.94l0.62,-2.71l0.62,-0.78l-0.51,-0.96l-0.67,-0.11l-0.12,-2.4l-0.54,-0.61l1.05,-1.75l0.4,-1.85l-1.71,-1.36l-1.21,0.23l-3.91,-1.47l-0.56,0.12l-0.61,1.02l-0.67,0.02l-2.62,-1.72l-0.52,-1.47l0.38,-1.35l0.8,-0.43l0.24,-1.02l1.17,-0.93l0.33,-0.77l-0.87,-1.94l0.89,-0.39l0.66,0.3l1.11,-1.32l-0.04,-2.19l0.6,-1.25l-0.58,-0.39l-0.1,-0.79l-1.31,-2.27l-0.1,-2.94l-0.48,-0.57l0.31,-2.28l-0.37,-0.8l0.51,-1.2l-0.23,-1.93l0.32,-1.21l-0.66,-2.25l0.28,-0.85l-0.14,-1.24l0.38,-0.42l0.13,-1.31l0.77,-1.85l0.82,-0.48l0.29,-0.62l1,0.34l0.38,-0.77l1.53,-1.2l0.67,-2.1l-0.43,-1.68l-1.56,-0.93l-0.88,-0.03l-1.14,-1.65l-0.23,-1.24l-1.97,-1.13l-0.18,-0.96l-0.58,-0.49l-1.85,-0.95l-0.87,-3.1l-0.78,-1.34l-1.04,-4.26l-0.83,-0.6l-0.66,-0.03l-0.2,0.62l-1.35,0.33l-1.11,0.94l-0.74,-0.2l-0.43,-1.56l0.05,-2.37l0.62,-1.32l-0.63,-0.53l0.34,-2.37l-0.24,-1.22l-0.94,-0.43l-1.22,-1.39l-0.43,-1.3l0.18,-1.57l-0.42,-0.6l-0.71,-0.03l-1.5,-1.09l-0.53,-1.05l-1.69,-0.11l-0.81,-1.37l-1.63,-1.19l-0.23,-0.68l0.33,-1.08l-1.43,-0.88l-0.95,0.67l-1.23,0.03l-0.2,-0.78l-1.13,-0.43l-0.25,-0.89l-1.21,-0.72l-0.13,-1.36l-0.54,-0.03l-0.21,0.61l-1.34,0.44l-0.7,-1.06l-1.89,-0.7l-0.85,0.04l-1.1,-1.97l-0.91,-0.13l-1.38,1.65l-0.52,0.18l0.04,-3.25l-1.59,-0.12l-0.45,0.44l-1.08,-0.29l-0.84,0.75l-0.63,-0.63l-1.63,0.86l-0.73,-0.1l-0.41,-0.91l-0.47,0.29l-0.78,-0.31l-1.1,0.2l-0.76,-1.3l-0.68,-2.28l0.27,-1.03l-0.41,-0.06l-0.76,-1.54l-0.81,-0.52l-1.76,-2.39l-0.77,0.06l-0.08,-0.43l-0.61,-0.15l-2.01,0.45l-1.99,-0.44l-0.58,-0.66l-0.08,-1.11l0.46,-0.63l-0.08,-0.73l-1.39,-1.2l-0.42,-0.9l-0.81,-0.42l-0.25,-0.79l-1.09,-0.33l-0.65,-0.69l-2,-0.08l-2.24,-1.28l-0.58,-1.63l0.24,-0.53l-0.48,-1.8l0.17,-1.1l-0.68,-1.42l-0.8,-0.22l-1.32,0.71l-0.77,-0.25l-1.01,-1.74l-0.98,-2.75l-1.61,-1.03l-2.03,-2.69l-1.38,-0.8l-0.22,-0.74l-0.85,-0.87h-0.67l0.12,-0.38l-1.03,-0.88l-0.54,0.42l-0.7,-0.02l-0.03,-0.44l-0.72,-0.2l-1.06,0.69l-0.76,-0.23l0.79,-0.67l-0.83,-1.61l-0.75,-0.33l-0.26,-1.14l0.68,-0.6l0.79,0.16l0.7,-1.65l-0.11,-0.99l-1,-1.43l-1.34,-0.78l-1.19,-2.52l-0.88,-0.85l-2.15,-0.96l-2.22,-0.08l-2.72,-1.32l5.52,-5.5l10.89,7.47l1.63,-6.02l-1.65,-1.65l-2.17,-6.34l0.56,-2.83l2.83,-3.31l5.88,-4.64l11,3.18l3.43,5.99l8.26,12.69l5.97,9.98l0.61,3.42l4.71,8.15l1.16,9.65l5.05,-2.28l2.04,1.47l6.39,3.5l7.88,-0.15l3.91,5.35l8.73,-5.57l7.43,-1.17l1.83,-3.94l1.44,-6.2l3.12,-1.5l3.6,0.86l2.9,4.16l2.64,-0.91l-0.14,3.3l1.74,0.7l1.54,1.72l1.53,0.79l9.64,3.05l5.58,3.95l2.49,6.58l1.36,0.59l0.52,-4.82l1.54,-0.68l0.9,0.49l0.66,-0.34l0.2,-0.72l0.83,-0.24l0.61,0.6l0.73,-1.38l0.78,-0.34l-0.27,-3.65l0.27,-2.25l0.46,-0.72l-0.2,-3.23l0.54,-3.09l0.56,-1.12l2.33,-2.31l0.43,-1.4l0.94,-1.01l4.01,-2.88l0.35,-0.67l0.36,0.08l2,-1.15l1.92,1.63l1.48,0.34l1.23,-0.87l0.13,-0.56l0.78,-0.71l1.84,-5.26l0.4,-2.18l1.52,-1.98l0.04,-1.07l-0.64,-0.5l-0.22,-0.79l0.13,-1.68l-0.93,-1.97l-0.08,-3.18l0.67,-2.03l-1.5,-5.26l-0.02,-0.74l0.51,-0.67l-0.27,-3.78l0.89,-0.76l0.02,-0.89l0.39,-0.42l0.02,-3.65l0.51,-0.88l0.07,-1.22l0.59,-0.34l0.19,-1.05l0.97,-0.38l-0.04,-1.4l0.72,-1.6l0.35,-0.06l-0.48,-1.06l-0.57,0.18l-0.08,-0.66l0.36,-0.35l-0.86,-0.62l0.47,-0.45l0.76,-3.47l0.96,-0.88l-0.41,-1.75l0.88,-2.99l-1.08,-1.34l-0.09,-0.58l1.65,-0.88l1.37,-1.36l1.31,-3.41l-0.49,-0.95l-0.19,-2.47l-1.98,-1.46l0.55,-1.27l1.07,-0.82l0.9,-2.03l0.98,-1l1.99,-0.36l1.78,-1l0.69,-0.83l0.41,-1.29l0.91,-0.4l0.24,-1.39l0.77,-0.43l0.5,-1.23l0.57,-0.39l-0.08,-1.74l2.73,-1.83l1.59,-1.59l1.08,-2.6l-0.2,-1.91l1.44,-1.64l0.31,-1.75l0.9,-0.56l1.96,-0.34l1.82,-0.94l1.95,-0.52l0.6,1.31l0.83,0.37l2.18,-1.25l2.03,-0.1l0.04,1.55l0.45,0.88l0.58,0.25l1.52,-0.76h0.97l0.77,0.62l0.61,1.2l1.24,0.87l0.79,-0.68l1.12,0.05l1.05,-1.37l5.23,-2.12l0.07,-0.71l-0.77,-1.18l0.26,-0.63l0.93,-0.79l1.31,-0.08l1.66,-2.11l0.87,-0.61l2.99,-0.29l0.93,-3.36l1.87,-1.47l2.25,-0.13l2.01,1.11l1.61,-1.16l4.87,-1.44l0.27,0.03L271.76,1.51z"},{id:"FI-11",title:"Pirkanmaa",d:"M107.14,626.33L107.83,626.6L108.13,629.09L107.72,629.81L108.37,630.96L105.52,632.06L105.31,632.99L105.82,638.55L103.91,639.12L102.76,639.03L100.18,640.18L98.01,642.92L99.21,643.83L100.12,643.96L100.03,644.96L100.31,645L100.53,644.31L100.45,643.65L100.91,643.95L100.77,644.83L101.88,645.04L101.94,645.71L101.63,645.98L102.25,647.44L102.89,648.05L103.9,648.05L104.56,648.76L104.41,650.17L105.95,650.76L106.1,651.46L104.48,652.17L104.81,652.95L105.45,652.54L107.39,655.14L107.21,656.29L106.76,656.51L106.97,656.87L106.61,658.25L106.04,659.26L105.39,659.09L104.21,659.63L104.34,660.07L103.87,660.49L103.47,660.37L102.63,661.3L102.87,663.07L101.6,663.22L101.81,664.13L102.58,664.9L101.65,665.16L101.84,666.03L102.84,665.6L102.97,664.68L103.29,664.63L103.39,664.94L103.79,664.87L103.66,666.01L104.08,666.7L103.4,668.12L102.04,666.93L103.16,669.69L101.5,670.8L101.39,672.2L100.15,673.52L99.53,673.18L101.89,677.86L102.34,678.18L102.58,677.88L104.01,677.98L104.21,678.98L103.72,679.14L104.29,680.86L102.22,681.35L102.56,682.78L102.16,682.05L102.1,682.84L101.67,682.64L101.04,682.93L101.26,684.04L99.24,683.26L98.77,683.46L99.79,686.92L98.76,687.68L100.43,689.75L101.52,693.28L103.33,693.32L103.5,693.67L103.63,693.31L105.51,693.33L107.91,694.42L108.29,694.02L112.25,696.92L114.37,696.79L114.62,697.61L115.08,697.42L114.73,696.57L116.25,696.59L118.25,695.57L120.26,695.86L120.62,694.89L121.62,695.08L121.22,697.57L125.09,701.04L121.52,702.42L121.32,701.97L120.58,701.91L120.2,702.5L120.97,702.89L120.98,703.97L122.09,704.41L120.27,704.93L120.35,705.28L122.07,705.84L121.21,708.32L121.21,708.32L123.54,708.96L124.43,708.72L125.94,711.66L127.02,711.5L127.95,712.05L127.37,710.82L128.07,710.23L129.02,709.98L129.94,710.33L130.27,709.66L130.9,709.9L131.03,709.57L131.64,709.91L131.2,710.2L131.58,710.64L132.31,710.15L132.66,709.42L132.66,709.42L134.84,709.32L134.84,709.32L135.69,708.97L136.44,709.51L136.42,710.15L137.36,709.86L138.26,710.38L139.71,713.58L140.5,712.61L140.1,710.98L138.97,709.59L139.52,709.44L139.55,708.85L139.89,709.05L140.93,708.16L140.51,707.2L138.21,707.95L138.49,706.33L137.08,705.83L138.55,704.42L139.19,704.22L139.9,704.71L141.36,704.13L145.83,701.42L146.82,701.74L148.33,701.19L149.42,701.52L149.15,700.64L149.34,700.15L152.33,699.69L154.54,696.92L153.48,695.8L153.16,694.97L153.9,693.74L154.72,694.17L157.27,693.13L157.62,693.3L157.78,692.79L158.31,692.85L159.17,691.78L159.51,691.92L160.64,690.9L163.18,689.48L163.72,690.45L166,691.23L166.82,691.11L167.44,691.64L168.25,688.59L169.42,691.82L170.66,691.56L173.19,690.62L172.91,689.94L173.98,688.13L173.98,688.13L173.22,686.13L173.72,684L173.4,683.61L173.92,682.05L172.69,680.59L172.06,677.93L175.9,679.69L175.9,679.69L174.54,677.66L174.39,675.99L175.04,673.77L172.89,673.32L174.1,671.94L174.14,670.43L173.26,669.83L171.96,670.49L171.55,672.57L171,670.26L170.19,669.29L169.89,668.22L170.79,665.64L171.4,666.32L171.4,666.32L172.11,666.54L172.11,666.54L172.55,664.81L172.4,663.75L171.18,663.29L169.66,663.29L169.05,661.62L169.05,659.04L170.42,658.43L171.18,657.52L166.93,653.11L163.28,648.4L163.13,646.88L163.73,644.9L167.08,643.23L168.23,641.08L167.36,639.53L166.18,639.11L166.38,634.8L164.77,633.97L164.07,633.16L162.71,629.98L160.96,628.79L160.85,629.25L158.75,630.74L158.95,631.93L158.51,632.28L157.98,631.07L157.87,631.59L157.66,631.51L157.69,630.94L157.41,630.92L157.3,631.35L155.65,631.24L154.24,629.27L153.37,624.95L152.94,625.42L149.78,625.43L147.47,623.84L147.29,622.44L146.96,622.12L146.39,622.31L145.61,621.09L145.25,617.82L145.25,617.82L144.59,616.85L142.37,615.96L141.68,612.99L141.98,611.4L141.57,609.53L140.61,609.46L140.57,611.18L139.7,611.22L139.51,608.85L138.55,609.97L138.93,610.75L138.85,611.6L138.09,610.87L134.09,614.71L128.96,614.38L129.41,617.53L128.04,616.52L127.11,616.97L126.36,616.78L125.28,616.03L124.86,615.18L124.55,615.52L124.3,615.34L124.68,614.98L124.2,614.5L123.88,614.79L123.53,614.54L123.57,613.61L121.65,614.74L120.87,616.91L121.3,617.32L121.29,618.06L120.45,618.17L120.23,618.59L119.85,618.4L120.08,619.09L119.53,619.96L109.6,624.23L107.46,624.15z"},{id:"FI-12",title:"Ostrobothnia",d:"M54.77,620.1l0.71,-2.03l-0.29,1.62L54.77,620.1zM56.18,615.74l0.32,-0.04l-0.02,0.61l0.42,0.22l0.05,2.41l-0.27,-0.11l-0.1,0.85l-0.47,-1.04l-0.04,0.64l-0.28,0.19l-0.12,-0.26l0.12,-2.61L56.18,615.74zM55.1,617.02l0.02,0.79l-0.46,0.24l0.3,-1.52l0.76,-1.27l-0.21,2.62l-0.11,-0.94L55.1,617.02zM55.25,613.61l0.39,0.86l-1.08,2.85l-0.1,-1.28l0.69,-1.19l-0.11,-0.83l-0.48,0.37L55.25,613.61zM51.17,602.82l0.73,0.76l-0.48,2.11l0.28,0.01l0,0.59l-0.62,-0.03l-0.58,-1.58L51.17,602.82zM50.64,591.48l0.71,-0.01l0.44,1.19l-0.61,1.43l-0.64,-0.71L50.64,591.48zM54.58,582.67l1.3,0.75l0.54,-0.17l-0.46,1.51l-2.51,0.73l-0.37,-0.34l-0.57,0.39l-0.63,-0.24l0.08,-0.55l0.46,-0.14l-0.26,-0.36l0.92,-0.33l0.24,-0.64L54.58,582.67zM54.56,578.51l0.62,0.67l0.34,-0.06l-0.24,0.36l1.1,1.43l0.21,2.05l-1.17,-0.99l0.23,-0.73l-1.28,-1.46L54.56,578.51zM61.57,576.35l-0.33,0.29l0.21,0.48l0.49,-0.04l-0.29,0.31l0.52,0.14l0.01,0.74l-0.52,0.23l-0.58,-0.58l-0.46,0.5l-0.59,-0.79l1.18,-1.37L61.57,576.35zM53.62,572.63l1.64,1.59l0.3,-0.06l0.35,2.96l-0.45,0.39l-0.25,-0.95l-0.6,0.21l-0.07,0.83l-0.56,-0.1l-0.77,-0.97l0.1,-1.14l0.36,0.91l0.33,-0.43l-1.29,-2.35l0.36,-0.43l0.32,0.08L53.62,572.63zM59.79,572.77l1.15,0.71l0.09,0.7L60,573.49l-0.07,0.3l-0.28,-0.16l0.37,-0.49l-0.5,-0.27l-0.13,0.22l-0.12,-0.52L59.79,572.77zM61.14,572.22l1.05,0.54l0.09,0.87l-1.34,-0.48l-0.13,-0.81L61.14,572.22zM55.22,571.65l0.55,1.45l0.37,-0.58l0.12,0.58l-0.14,0.46l-0.79,0.29l-0.66,-0.68l-0.11,-0.84l0.58,-0.09l-0.21,-0.58L55.22,571.65zM60.8,570.25l-0.04,0.37l0.64,0.13l0.23,-0.3l0.17,0.52l0.74,0.48l0.81,-0.2l-0.81,1.44l-0.63,-0.23l0.23,-0.51l-0.68,0.1l-1.3,-0.66l-0.45,-0.84L60.8,570.25zM62.92,567.58l0.48,1.08l-0.53,0.75l0.58,1.08l-0.95,0.84l-0.92,-1.12l0.62,-0.54l-0.64,-0.17l0.73,-1.17l-0.09,-0.73L62.92,567.58zM67.52,566.67l0.28,0.5l-0.4,0.4l-0.83,-0.12l0.3,-0.68l0.33,0.01l-0.11,-0.45L67.52,566.67zM57.75,554.68l0.89,0.54l-0.06,0.63l-0.86,-0.21l-0.2,-0.34h0.32L57.75,554.68zM72.25,551.32l1.62,1.39l-0.17,0.55l0.34,0.06l-0.59,0.92l-0.81,-0.19l-0.78,-1.19l0.05,-0.96l-0.5,-0.64L72.25,551.32zM56.34,550.78l0.49,-0.01l0.13,0.6l-0.63,0.61l0.14,0.55l0.56,-0.08l0.27,-1.14l0.43,1.12l-0.34,0.2l-0.09,0.66l-0.47,-0.21l-0.42,0.99h-0.33l-0.27,1.65l0.52,0.94l1.32,-0.29l-0.41,-0.65l0.25,-0.12l0.44,0.45l1.05,0.25l0.15,-0.83l-0.3,-0.11l0.88,-0.52l-0.17,-0.22l0.45,-0.48l0.14,0.41l0.69,-0.43l-0.08,-0.65l0.21,0.33l0.39,-0.27l0.03,0.3l1,0.31l-0.19,0.4l0.37,0.09l0.87,1.5l-0.39,0.37l-0.06,1.23l0.57,0.66l-0.1,0.64l-1.12,0.1l-0.47,-0.45l0.4,1.39l-0.56,-0.62l-0.25,0.63l-0.69,0.03l0.15,-1.64l0.5,-0.26l-1.06,0.15l-0.04,1.1l-0.31,-0.22l-0.66,1.45l-0.73,0.04l0.17,0.37l0.7,-0.18l-0.45,0.78l0.3,0.5l-0.46,-0.2l-0.36,0.45l-0.86,-0.08l-1.44,-0.93l0.1,-1.03l-0.38,-0.93l-0.49,0.87l-0.84,-0.07l-0.04,0.32l-0.41,-0.21l-0.46,-1.09l0.28,-0.33l-0.31,0.04l-0.41,-0.59l0.09,-0.72l0.35,-0.03l-0.11,-0.46l-1.1,-2.16l-0.26,0.08l0.65,-1.01l-1.36,-0.82l0.34,-0.4l-0.27,-1.27l0.65,0.26l0.33,1.06l0.15,-0.19l1.01,0.57l0.18,-0.29l0.65,0.41l-0.07,-1.36l0.3,-0.23l0.3,0.25l0.57,-1.32L56.34,550.78zM71.06,550.19l0.52,0.63l-0.22,0.55l-0.38,-0.13l0.08,1.06l0.69,1.12l-1.13,-1.02l-0.33,0.9l0.29,0.48l-0.2,1.36l-0.68,0.17l-0.45,-0.47l-0.27,-1.6l0.42,-0.26l-0.58,-0.48l0.94,-0.68l0.19,-1.18l0.74,0.08L71.06,550.19zM88.86,550.15l0.24,0.39l-0.18,1.04l-0.28,-0.57L88.86,550.15zM87.9,549.32l0.46,-0.04l0.18,0.33l-0.03,2.5l-0.53,1.75l-0.42,-0.16l-0.32,0.4l-1.02,-0.47l-0.19,-0.79l-0.4,0.11l0.13,0.35l-0.66,-0.15l1.06,0.65l-0.16,1.58l-0.5,-0.23l0.09,0.41l-0.59,-0.49l-0.16,0.27l-0.71,-0.57l-1.46,-0.23l0.17,-0.31l0.81,-0.11l-1.32,-0.96l0.09,0.49l-1.23,-0.26l-1.2,0.23l0.56,-3l1.02,1.02l0.28,-0.41l-1.04,-0.8l0.65,-0.67l1.07,1.16l0.38,0.86l-0.08,1.07l0.47,0.09l0.66,-0.52l-1.06,-1.67l-0.01,-0.73l0.31,0.58l1.15,-0.92l0.55,0.11l0.11,0.55l0.52,-0.46l-0.15,0.32l0.27,0.21l-0.32,0.08l0.33,0.56l0.5,-0.65l0.83,0.34l0.07,0.7l0.53,-0.54L87.9,549.32zM59.84,547.19l2.6,0.3l-0.51,0.4l0.33,0.82l-0.17,0.63l-0.83,0.78l0.27,0.43l-0.33,0.86l0.21,0.12l-1.81,1.97l-0.39,-0.19l0.6,-0.98l-0.18,-0.68l0.63,-0.36l-0.42,-0.06l0.29,-0.39l-1.2,0.14l-0.7,0.75l-0.49,-0.43l-0.02,-0.79l0.41,-0.5l-0.65,0.03l-0.07,-0.3l-1.22,0.3l0.78,-0.51l-0.31,-0.59l0.47,-0.8l-0.35,-0.17l0.53,-0.13l0.09,0.41l0.34,-0.03l0.92,-0.81L59.84,547.19zM81.56,545.69l0.22,0.66l0.57,-0.79l0.94,0.24l-0.13,0.23l0.72,-0.03l0.25,0.68l-0.72,-0.17l0.1,0.29l-0.27,0.04l0.58,0.22l0.12,0.51l-1.11,0.6l-0.86,1.33l-0.38,-0.68l-0.52,-0.13l-0.64,0.11l-0.32,0.72l-0.97,0.36l-0.04,-0.73l0.58,-0.19l-0.24,-0.66l0.37,-0.1l0.03,-0.68l0.85,-0.77l-0.12,-0.75l0.42,0.13l0.2,-0.81L81.56,545.69zM56.87,545.28l0.43,0.39l-0.49,1.6l-0.97,0.57l-0.55,-0.14l-0.5,-0.53l0.51,-1.31l0.67,0.06l0,-0.4L56.87,545.28zM70.86,545.18l0.25,0.68l-0.46,0.54l-0.67,-0.03l0.32,-0.44l-0.58,0.13l0.3,-0.33l-0.5,0.04l0.13,-0.61l0.59,0.33L70.86,545.18zM73.71,542.79l-0.45,0.06l0.16,-0.3L73.71,542.79zM73.05,541.98l0.21,0.06l-0.47,0.17l0.05,-0.39L73.05,541.98zM72.45,541.13l0.47,0.04l-0.39,0.76l0.33,0.47l-0.27,0.45l0.44,0.1l-0.87,0.14l0.26,-0.32l-0.32,-0.17l-0.85,0.29l0.16,-0.33l0.74,-0.09l0.1,-0.59l-0.34,0.29l-0.44,-0.47l0.87,0.09l0.02,-0.26l-0.76,0.04l0.94,-0.16L72.45,541.13zM71.89,541.35l-0.14,-0.32l0.33,-0.17L71.89,541.35zM74.15,540.93l0.62,0.14l-0.46,0.32l0.68,-0.14l-0.02,0.56l0.31,0.02l-0.26,0.13l0.28,0.13l-0.22,0.68l0.25,-0.15l-0.25,0.42l-1.33,-0.26l0.6,-0.3l-0.15,-0.77l-0.7,0.03l0.14,-0.32l0.54,-0.02l-0.59,-0.49L74.15,540.93zM73.85,540.77l-0.32,-0.04l0.54,-0.21L73.85,540.77zM92.87,528.92l0.39,-0.03l0.66,0.98l-0.54,1.47l-0.15,-0.96l-0.77,-0.01L92.87,528.92zM100.54,517.61l0.82,0.37l0.48,0.72l-1.05,-0.27l-0.46,1.75l-0.77,-1.08l0.48,-1.22L100.54,517.61zM113.42,517.1l6.84,5.26l0.27,0.55l0.32,-0.18l0.55,-2.11l1.93,-1.47l1.18,0.46l0.35,-0.15l-0.32,-0.01l0.22,-0.25l0.63,0.17l0.41,0.63l0.49,-0.17l0.92,1.12l0.28,-0.3l0.01,-1.61l0.65,-1.08l8.39,7.37l-1.11,1.43l-1.77,-0.97l-1.21,1.42l-2.05,1.21l-0.77,-0.19l-0.6,-0.78l-0.05,-1.74l-0.51,0.84l-0.59,-0.06l0.5,1.45l-1.01,0.8l0.42,0.64l-0.22,0.59l-0.66,-0.57l-0.51,0.19l2.18,2.22l0.57,-0.57l0.64,0.26l0.79,-1.08l0.83,1.46l-0.72,0.8l0,0.44l0.75,-0.14l-0.13,0.49l0.37,0.3l-0.25,0.41l2.2,1.58l0.23,4.95l0.34,0.74l-0.24,0.11l0.02,1.11l1.57,3.72l-0.36,0.23l0,0l-2.23,-1.4l-1.06,-1.39l0.15,-0.26l-1.35,-1.43l0.23,-0.43l-0.72,-1.4l-0.38,-0.13l-0.36,0.41l-1.57,-1.04l-1.63,-0.29l-0.85,-1.12l-4.11,2.03l-0.82,1.54l-0.98,3.54l-2.98,3.61l-0.96,-1.3l-1.52,0.35l-0.34,-1.25l-0.82,0.1l0.06,0.53l-0.92,-0.04l0.25,2.71l-3.14,-1.5l0.47,-0.38l-0.88,-0.35l0.16,0.73l-0.34,-0.17l-0.09,0.25l0.45,0.43l-1.49,0.04l0.17,-0.28l-0.9,-0.43l-0.78,0.48l-0.53,-0.57l-1.37,0.11l0.05,0.46l0.66,-0.33l0.38,0.9l-0.94,0.67l-0.26,-0.35l-2.22,1.42l0.81,1.42l-2.12,1.31l-0.38,-0.33l-1.14,1.24l-0.16,0.89l1.81,1.14l-0.4,0.57l0.32,0.04l0.67,1.3l-1.17,0.66l-0.62,1.47l1.16,-0.52l0.28,0.55l1.71,-0.85l0.13,4.75l-0.65,-0.39l-0.87,0.13l0.47,0.26l0.12,1.31l-0.52,0.3l0.15,0.4l-1.48,0.63l1.16,0.29l-0.28,0.77l-0.69,-0.89l-2.07,1.37l0.8,1.07l-0.21,0.22l-0.18,-0.46l-0.48,0.54l-0.32,-0.21l-0.21,0.37l0.24,0.08l-1.49,2.13l-0.49,2.36l-1.45,1.88l0.38,0.57l-0.66,1.4l0.05,0.72l-0.67,0.12l0.61,3.22l-1.08,0.62l-2.19,4.31l-0.93,0.31l-2.4,2.78l-2.41,-1.08l-0.13,0.44l-1.65,-0.55l-0.21,0.31l-5.83,-2.87l-0.66,-0.5l-0.08,-0.54l-0.43,0.12l-0.35,-1.88l-1.88,-1.25l-0.25,1.15l-1.12,1.82l0.03,4.49l0.56,2.4l1.41,1.92l-1.33,1.23l-0.29,-0.13l0.27,-0.69l-0.2,-0.42l-0.56,1.98l-0.9,0.6l-0.37,0.95l-1.01,0.43l-0.22,0.98l-0.75,0.8l-1.07,0.46l0.18,3.2l0.52,0.13l-0.09,1.12l-2.12,6.43l-0.84,-0.59l-0.24,0.33l1.13,0.86l0.15,2.98l-0.87,1.15l0.66,0.4l0.47,1.07l1.95,-0.37l0.05,0.36l0.15,-0.39l0.67,-0.19l1.23,0.87l-0.06,1.02l-0.54,0.69l0.44,0.63l-0.29,4.1l0.48,0.05l0.17,-0.51l1.13,0.86l1.24,2.45l-1.87,0.38l-1.35,1.76l1.22,1.36l-0.31,1.59l-0.43,0.31l0,-0.59l-0.43,0.44l-0.8,-0.52l0.04,2.38l-0.53,1.02l0.78,2.69l-0.7,1.34l0.62,1.38l0,0l-4.03,-0.37l-3.05,1.11l-1.47,2.22l-1.62,1.31l0,0l-0.6,-0.79l0.47,-1.08l0.21,0.17l0.2,-1.29l-0.36,-0.15l-1.34,1.11l-0.23,-0.46l0.37,-0.4l0.71,-3.73l-0.17,-1.08l0.47,-2.31l-0.26,-2.92l-0.25,0.44l-0.01,-0.31l0.68,-1.19l0.26,0.29l-0.28,1.03l0.34,0.37l0.66,-0.2l0.05,-2.99l1.2,-1.29l0.06,-0.49l0.25,0.13l0.2,-1.16l-0.2,-0.31l-0.51,0.85l-0.08,-0.84l-0.43,-0.07l0.33,-1.69l-0.27,0.17l0.04,-0.95l-0.52,0.12l-0.35,1.17l-1.08,0.21l0.03,-0.86l0.79,-1.12l0.41,-2.47l-0.3,-0.34l-0.31,1.35l-0.28,-0.28l-0.28,0.2l0.29,-0.82l-0.39,0.36l-0.45,-1.04l0.34,-0.91l0.36,0.98l0.46,-0.69l0.17,0.65l0.65,-3.63L59.9,617l-0.59,0.3l-0.69,1.48l-0.04,-2.13l-0.48,0.46l-0.08,-0.94l0.5,-1.37l-0.32,-0.03l-0.31,0.98l-0.71,0.22l-0.38,-0.01l-0.72,-0.87l-0.12,-0.52l0.75,-1.81l-0.3,-0.19l0.27,-0.6l-0.51,0.26l-0.26,0.64l-0.22,-0.31l-0.53,0.83l-0.38,0.03l-0.25,0.6l-0.04,-0.54l-0.28,0.25l1.29,-5.04l-1,2.3l-0.14,-1.16l-0.88,0.5l-1.06,-1.19l0.85,-0.56l0.57,-2.28l-0.25,-0.18l-1.13,0.64l-0.14,-1.92l0.8,0.04l0.75,1.06l0.43,-0.71l-0.02,-0.71l-0.56,-0.22l0.01,-0.94h0.41l0.13,-0.82l0.87,-0.53l0.13,-0.69l0.98,-0.35l-1.17,-0.41L54.92,600l0.36,-0.22L55,599.65l-1.55,0.58l-0.26,-1.89l-0.92,1.4l-0.23,1.25l-0.74,-0.71l-0.05,-0.67l0.78,0.13l-0.23,-0.4l-0.3,0.1l0.02,-1.56l0.18,-1.17l0.67,-1l-0.42,-0.22l-0.4,0.29l0.15,-1.32l0.32,-0.14l-0.04,0.42l0.96,0.13l0.74,-0.63l-0.14,-0.85l0.64,-0.52l0.19,0.18l0.37,-1.3l-0.04,-0.88l-0.97,0.26l-0.3,-0.45l-0.64,-3.08l0.54,-0.31l0.05,-0.64l0.58,0.06l0,-0.24l0.45,-0.01l1.02,0.96l0.24,-0.27l0.02,-1.1l1.13,-0.98l0.05,-2.29l0.59,0.03l-0.33,-0.48l0.27,-0.36l-0.64,-0.52l0.09,-0.37l0.51,0.46l0.87,-0.51l2.34,1.44l1.38,-0.35l-0.01,-1.63l0.67,-1.62l-0.11,-1.4l0.32,-1l1.67,-0.73l-0.51,-1.08l0.04,-0.77l0.63,-0.21l-0.05,-0.51L63.83,573l0.42,-0.39l-1.02,-0.75l0.67,-0.13l0.12,-0.58l0.47,0.32l0.17,1.08l0.39,0.13l-0.04,-1.04l-1.25,-1.65l0.19,-0.65l0.94,0.18l0.25,-0.37l0.36,0.46l0.24,-0.3l-0.29,-0.63l0.17,-0.71l0.8,-0.41l0.62,0.88l0.34,-0.28l0.1,0.78l0.34,0.01l0.12,0.51l0.49,0.24l0.37,-0.59l0.23,0.75l0.9,0.74l1.03,-0.89l-0.05,-1.02l-0.57,-0.06l-0.2,0.37l-0.35,-0.73l-1.27,-0.58l-0.47,-1.15l0.43,-0.64l-0.93,0.27l0.1,-0.9l0.59,-0.23l-0.45,-0.49l-0.31,0.41l-0.54,-0.09l-0.11,-0.78l-1.43,-2.04l-0.19,-0.99l0.41,-0.93l0.81,0.02l0.04,0.35l0.38,-0.4l0.61,0.04l-1.42,-0.64l-0.58,0.32l0.07,-2.78l0.21,-0.55l0.89,-0.23l-0.25,-0.88l-0.33,-0.04l0.48,-0.32l-0.4,-0.46l0.46,-0.26l-0.15,-0.24l0.83,-0.19l0.09,-0.83l0.34,0.16l-0.33,0.94l0.32,1.49l-0.33,0.38l0.66,0.14l0.05,0.55l1.01,0.87l0.74,-0.03l-0.29,0.61l0.36,-0.17l0.72,0.42l0.66,-1.74L72,556.9l0.76,1.3l0.65,-0.33l-0.7,-0.31l-0.15,-1.28l0.51,-0.5l0.24,0.67l0.77,-2.07h0.39l0.27,-0.48l0.24,0.08l0.05,1.35l0.6,-0.04l0.59,-0.92l0.1,0.52l0.4,0.17l0.58,-1.04l0.7,-0.26l0.56,0.26l0.16,0.94l-0.4,0.62l0.3,0.43l0.61,-1.23l0.58,1.18l0.05,-1.08l0.73,-0.13l0.06,0.87l0.36,0.04l0.28,-0.46l0.14,0.46l0.02,0.53l-0.34,0.48l-0.17,-0.2l-0.19,0.72l0.43,-0.2l0.31,0.65l-0.17,0.58l-0.62,0.26l-0.69,-0.5l-0.54,0.15l-0.17,0.36l0.16,0.36l0.21,-0.28l0.35,1.62l-1,0.02l0.64,0.74l0.08,0.62l0.32,-0.13l0.84,0.81l0.34,-0.18l-0.88,-1.48l0.04,-1.31l0.66,-0.58l0.98,0.6l0.25,-0.33l-0.33,-0.91l0.25,-0.45l-0.7,-1.12l0.21,-1.06l0.43,0.51l1.57,-0.6l0.21,0.48l-0.26,1.09l0.52,0.45l0.12,-0.38l0.27,0.22l0.13,-0.55l0.73,-0.19l0.13,-0.44l0.9,0.16l0.19,-0.72l0.63,-0.58l1.38,0.74l-0.12,-2.1l0.55,-0.49l-0.09,-0.57l1.06,-0.42l-0.14,-0.82l0.73,0.12l0.92,1.51l0.26,-0.23l0.62,0.41l0.22,-0.92l-0.39,-0.66l0.13,-0.48l-0.42,-0.38l0.5,0.21l1.01,-1l-1.68,-3.28l-1.5,-0.88l0.18,-0.96l-0.26,-0.5l-0.97,-0.23l-0.08,-0.46l-0.86,-0.66l-0.08,-0.6l-0.9,-1.18l0.14,-1.61l0.78,-0.34l0.98,0.3l1.37,-0.55l0.82,0.97l0.59,1.65l0.1,-0.92l0.77,1.32l1.1,0.61l-2.7,-3.13l-1.12,-2.14l0.21,-0.44l-0.36,-0.43l0.69,-0.87l-0.05,-0.49l1.05,-2.03l-0.4,-0.83l1.72,0.55l-0.31,1.53l-0.85,0.25l0.8,0.44l-0.15,0.46l0.61,1.25L93,536.93l-0.03,-0.39l-0.38,0.18l-0.27,0.59l0.74,0.04l0.31,-0.47l0.24,0.72l0.46,0.24l-0.21,0.62l0.29,1.29l0.71,-1.23l0.39,1.22l0.06,-2.67l1.09,-2.14l-0.73,-1.61l0.56,0.05l-0.03,0.43l0.35,0.05l-0.36,-1.21l0.39,0.83l0.73,0.16l-0.42,-1.52l0.71,-0.75l-0.22,-0.75l-0.28,0.04l-0.55,1.18l-0.6,0.37l-0.26,-1.09l-1.08,0.32l0.31,-0.37l-0.24,-0.56l0.46,-0.33l0.13,0.45l0.87,-0.07l0.02,-0.32l0.5,-0.07l-0.12,-0.7l0.41,0.52l0.01,-0.64l0.73,-0.19l-0.3,-1.04l0.22,-1.29l0.65,-0.3l0.36,-1l0.78,-0.08l0.58,0.55l0.67,-2.19l-0.09,-1.87l1.07,0.64l-0.04,0.72l-0.27,-0.35l-0.2,0.43l0.15,0.95l0.55,-0.32l-0.13,-0.66l0.34,-0.05l0.43,0.84l0.13,-0.27l0.28,1.04l0.43,-0.49l-0.25,-2.03l0.41,-0.14l0.94,0.76l0.17,-0.32l0.49,1.07l0.59,0.44l-0.27,1.18l0.41,1.08l0.07,-2.09l1.3,1.02l0.66,1.73l0.4,-0.15l0.29,-1.17l-0.87,-0.96l0.24,-1.03l-0.4,-0.34l0.13,-0.48l0.24,0.32l0.28,-0.14l0.08,0.5l0.4,-0.12l-0.51,0.53l0.44,0.54l0.22,-0.53l1.04,-0.07l-0.17,-1.28l0.39,0.11l0,-0.38l0.43,-0.25l0.27,0.64l0.27,-0.67l-0.35,-0.47l-1.36,-0.54l0.08,-0.45l-0.34,0.1l-0.03,0.4l-0.62,-0.86l1.23,-0.38l-0.25,-0.57l0.3,0.1l-0.09,-0.37l1.62,0.43l-0.76,-1.52l0,0l0.33,0.57l-0.05,-0.65l1.87,-0.38l0.02,-0.4l0,0l0.52,0.58L113.42,517.1zM105.48,516.86l0.34,-0.04l0.7,1.04l0.82,-0.25l0.21,0.48l-0.43,1.14l-0.34,0.07l-0.2,1.79l-0.21,-0.83l-0.82,0.06l0.34,0.14l0.02,0.76l-0.11,0.43l-0.65,-0.17l0.34,0.61l-0.3,0.28l-1.4,-0.64l-0.65,-1.41l0.21,-0.37l-0.86,-0.64l0,-0.4l0.87,-0.53l0.42,-0.73l0.74,-0.11l0.7,-0.9L105.48,516.86zM102.31,515.98l0.23,0.7l-0.35,0.21l0.11,0.56l-0.49,-1.86L102.31,515.98zM106.23,512.3l0.44,-0.2l0.49,0.54l0.57,-0.35l1.04,1.96l0,0l0.5,1.15l-0.27,0.68l0,0l-0.42,-0.1l-0.14,0.37l-0.74,-0.24l0.11,1.02l-0.68,-0.75l-0.49,0.4l-0.51,-0.9l-0.09,0.48l-1.57,0.06l0.27,0.42l-0.6,0.51l-0.83,-0.54l-0.05,-0.4l-0.5,0.04l-0.49,-1.05l0.91,-0.2l-0.3,-0.65l0.37,0.03l-0.05,-0.58l0.49,0.57l-0.27,-1.17l0.57,-0.33l0.04,0.46l0.31,-0.47l2.52,0.55l0.09,-0.43l0.55,0.04l-1.31,-0.46l-0.3,-0.69L106.23,512.3zM105.03,510.83l0.67,0.12l0.06,1.28l-0.95,-0.67L105.03,510.83zM105.8,507.57l-0.07,0.68l-1.14,-0.55l0.77,-0.72L105.8,507.57z"},{id:"FI-13",title:"North Karelia",d:"M284.25,519.64L287.86,512.33L287.35,511.38L289.21,510.59L301.1,513.87L313.76,512.8L326.52,510.77L327.86,520.27L329.57,523.41L332.69,520.16L335.86,519.56L335.86,519.56L338.75,523.08L339.05,524.08L344.22,530.04L344.83,532.03L348.92,534.85L352.04,540.46L361.83,544.84L363.93,547.46L366.56,548.32L366.91,549.78L368.04,551.85L369.32,552.14L371.84,554.36L373.26,555.04L374.07,556.48L376.26,558.12L376.25,559.76L376.8,560.94L376.81,563.59L377.33,565.97L378.11,566.98L380.19,568.49L381.09,570.15L382.27,570.58L383.43,571.85L383.04,573.15L384.72,573.86L387.39,579.98L383.22,587.76L383.53,588.68L382.68,588.62L380.81,595.18L380.94,596.23L380.54,598.05L379.66,598.52L375.73,608.52L374.54,608.88L373.81,612.2L372.96,612.55L366.89,619.84L367.35,620.3L366.78,621.77L365.49,621.47L363.33,623.82L362.53,624.2L362.46,624.85L359.68,628.4L357.67,628.4L356.79,629.75L356.98,630.86L355.97,632.99L350.94,640.42L348.8,642.69L347.87,644.16L346.54,645.04L346.71,646.45L346.36,647.09L345.49,647.23L343.49,649.97L342.96,650.07L343,650.66L341.31,652.74L341.31,652.74L340.93,651.92L339.79,652.44L322.63,661.51L322.63,661.51L323.01,660.54L325.16,658.81L326.36,656.72L326.8,654.69L326.72,653.68L326.02,652.57L326.95,651.87L324.4,648.54L324.43,647.02L325.84,644.26L322.88,641.03L322.98,640.61L320.97,640L319.42,637.14L317.79,629.03L318.47,626.55L317.25,625.43L314.68,620.02L314.15,616.11L313.3,614.74L312.09,614.04L311.09,615.14L310.34,614.67L309.84,615.37L310.03,616.18L308.29,615.72L307.76,615.03L308.12,614.27L307.31,613.5L308.31,608.94L307.25,608.83L305.9,607.73L304.81,607.44L305.87,606.99L305.7,606.2L304.93,605.87L302.83,603.8L302.89,602.99L300.31,601.37L297.99,598.57L294.34,597.96L293.66,597.38L293.66,597.38L293.66,597.38L293.66,597.38L293.66,597.38L293.66,597.38L293.74,596.54L295.17,594.88L293.29,592.32L292.99,591.36L293.3,590.28L294.51,589.11L295.7,589.29L296.67,587.54L296.57,586.59L297.53,585.47L298.05,585.11L299.33,585.69L299.89,586.88L301.55,587.76L302.54,589.33L302.89,589.23L303.71,587.19L307.85,584.27L305.08,582.33L305.13,581.73L304.76,581.8L303.66,579.77L302.74,579.15L302.5,577.94L303.5,578.73L304.55,578.54L304.18,577.81L304.46,577.88L304.42,577.59L303.51,577.26L303.84,576.35L306.86,574.53L305.92,572.68L302.25,570.85L301.9,570.28L300.47,569.51L299.25,566.74L295.4,561.43L295.09,560.52L292.33,559.05L293.88,556.44L293.55,555.72L294.38,555.33L294.53,554.69L295.36,554.21L295.24,553.35L294.72,553.34L295.62,552.73L295.42,552.32L296.31,551.43L297.03,546.07L294.02,543.5L293.54,540.31L292.07,536.08L292.36,535.14L293.03,534.62L293.56,535.1L294.6,534.21L294.18,533.68L293.77,533.83L292.73,533.34L292.38,533.04L292.5,532.6L292.15,532.58L291.52,526.62L292.13,525.46L291.5,524.54L290.38,523.62L288.35,524.09L287.51,523.75L286.36,521.79z"},{id:"FI-14",title:"Northern Ostrobothnia",d:"M162.53,424.86l0.82,-0.34l0.54,-1.26l1.76,-1.74l1.22,0.1l0.77,-0.34l1.59,0.3l2.34,-1l0.76,0.24l0.89,0.86l0.38,0.81l-0.47,-0.03l0.04,0.84l0.64,-0.26l0.6,0.26l0.97,-0.17l0.96,0.45l1.4,-0.09l0.99,0.95l-1.2,0.91l-1.37,0.06l-1.78,-0.23l-0.09,-0.56l-0.63,-0.43l-1.3,-0.07l-0.64,-0.46l-1.33,0.29l-0.03,0.61l1.05,-0.48l-0.38,0.67l0.08,0.62l0.59,-0.14l0.17,0.9l0.5,0.11l0.66,1.51l-0.34,0.93l0.17,1.56l-2.63,1.56l-0.07,0.42l-0.7,-0.3l-0.15,-0.68l-0.77,-0.34l-0.11,-1.06l0.57,0.02l-0.15,-0.6l-1.51,0.33l0.9,0.57l-0.81,0.4l-1.62,0.25l-0.59,-0.43l-0.6,-0.75l0.02,-0.76l-1.3,-1.34l0.01,-0.33l0.3,0.04l-0.48,-0.61l0.23,-0.33L162.53,424.86zM336.6,352.33l-0.17,-3.36l-0.61,-1.42l0.18,-0.27l-0.28,-0.23l-1.38,-6.3l-6.92,-11.2l-0.44,-0.08l0.3,-0.44l-4.24,-12.61l0,0l-10.01,0.06l-0.1,1.9l-17.9,-6.21l-0.95,5.8l-2.01,0.31l-0.41,-0.35l0.22,1.15l-0.45,-0.01l-0.29,1.44l-0.8,-0.02l0.13,2.99l-0.45,1.04l1.66,5.03l0.39,0.28l1.15,-0.13l0.17,1.13l0.53,0.32l0.75,-1.11l1.99,0.5l-0.19,0.67l0.55,0.7l-0.07,0.95l-0.64,0.49l0.41,0.4l-0.43,0.73l1.05,1.69l-1.66,1.88l-0.08,1.97l-0.86,0.68l-2.59,-0.02l0.63,2.87l0.55,0.41l-0.43,1.12l2.06,0.76l0.29,0.66l0.49,0.08l0.04,0.65l0.76,-0.53l0.6,0.54l-0.97,0.82l0.51,0.74l-0.07,1.72l-2.28,0.13l-0.71,1.04l-1.72,-0.07l-0.05,-0.92l-1.62,-0.74l-0.08,0.42l-1.9,0.03l-0.07,1.04l-2.19,0.24l-0.02,-0.92l0.64,-0.73l-1.93,0.46l0.53,0.46l0.02,1.15l0.29,0.13l-0.22,0.85l-0.55,-0.19l-0.19,0.24l0.11,0.6l1.92,1.11l0.85,2.22l1.53,2.1l0.2,3.5l-1.57,0.1l-7.68,3.41l-1.88,-0.48l-0.63,-0.56l-7.43,-0.55l-0.2,-0.59l-0.39,0.05l0.36,0.22l-0.12,0.3l-4.42,-0.33l0.17,-0.79l0.84,0.16l0.36,-1.09l-0.33,0.02l-0.35,0.79l-0.59,-0.22l-2.34,-4.62l-1.27,-4.64l-1.8,0.44l-1.08,2.02l-0.78,0.27l-3.02,-2.87l-1.04,1.54l0.24,0.44l-0.49,-0.08l-4.86,7.45l-0.54,0.05l0.2,0.44l-0.36,0.56l-0.18,-0.18l-0.03,0.49l-1.95,3.07l0.39,0.51l-0.44,0.22l-0.21,-0.33l-1.45,2.24l-0.59,0.28l0.25,0.48l-0.86,0.9l-1.2,-0.66l-0.9,0.42l-0.01,0.81l0.43,0.03l0.01,0.63l-1.17,0.09l-0.14,-1.18l-4.38,2.01l-4.99,-0.27l-0.08,-0.24l-0.19,0.71l-0.64,-0.77l-8.77,-0.29l-7.13,-0.87l-0.04,-7.56l-11.71,6.31l-11.85,-0.15l-2,1.14l-1.65,3.25l-2.52,1.36l-1,1.16l-0.24,-0.12l-1.95,3.7l-1.45,1.47l0,0l0.12,1.65l0.66,-0.58l0.25,0.46l-0.02,1.41l0.22,-0.8l0.2,-0.15l0.12,0.39l0.54,-1l0.45,0.6l0.48,-1.67l-0.2,1.37l0.51,0.47l0.56,-0.23l0.34,0.29l-0.42,0.25l0.17,0.99l0.92,0.51l0.97,1.58l-0.2,0.39l0.75,0.62l-0.17,0.6l0.52,1.03l0.87,-0.32l0.43,0.56l-0.6,0.16l0.37,0.52l-0.18,0.22l0.87,0.98l-0.84,0.02l-0.08,0.57l0.85,0.35l0.09,0.28l-0.7,-0.07l0.87,0.51l0.23,0.71l-0.86,0.28l-0.37,1.13l-0.31,-0.08l-0.46,0.58l-0.58,-0.75l-0.73,0.05l-0.09,0.63l0.19,0.79l0.88,0.71l-0.12,0.21l-0.7,-0.22l0.28,0.52l-0.5,0.12l0.01,0.33l1.75,-0.11l0.65,0.67l0.08,0.76l-1.95,0.04l0.31,1.02l-1.23,0.18l0.22,1.09l-0.31,0.22l1.35,0.71l0.17,0.66l0.8,0.67l-0.27,0.53l-0.64,-0.26l0.17,0.57l-0.83,0.44l-0.06,0.39l0.14,0.27l1.48,-0.18l0.57,0.41l0.13,0.4l-0.76,-0.02l-0.11,0.66l-0.57,0.39l0.94,0.16l-0.04,0.34l0.43,-0.11l0.32,0.64l-2.26,-0.38l0.31,0.19l0.05,1.01l-0.68,-0.26l-0.22,0.3l0.44,0.53l0.46,-0.1l0.34,0.34l-0.33,0.15l-0.14,0.79l-0.61,-0.01l0.59,1.01l-0.15,0.66l-0.88,0.44l-0.49,-0.38l-0.19,0.29l0.36,2.52l-0.34,0.74l2.27,0.28l-0.05,0.27l0.5,-0.02l0.84,1.12h0.82l0.6,0.56l-0.31,0.6l1.16,2.27l-0.39,-0.08l-0.09,0.29l0.83,1.21l-0.3,0.73l0.13,1.5l-0.58,0.07l-0.1,0.45l0.67,1.04l2.26,1.28l0.08,1.46l-0.84,0.64l-0.73,-0.11l-0.3,0.26l-0.48,-0.3l-0.25,-0.84l-1.73,-0.9l-0.83,-1.38L185.7,428l-0.14,0.27l-0.46,-0.74l-0.73,0.08l-1.25,-0.57l0.92,0.88l-0.38,0.34l0.07,0.93l-0.61,0.16l0.65,2l3.88,3.44l0.78,-0.47l0.62,0.2l-0.12,0.42l0.76,0.6l0.05,0.5l-0.35,0.11l0.32,0.41l-0.69,0.21l-0.4,1.65l-0.43,-0.11l0.13,0.62l-0.34,0.21l0.55,0.37l-0.69,0.08l-0.54,1.1l-1.29,0.08l-0.49,-0.32l0.67,-0.22l-0.38,-1.47l0.57,-0.12l-1.27,-1.25l-0.52,0.16l0.04,0.44l-0.33,-0.42l-0.46,0.15l-0.74,-1.05l-0.04,-0.61l0.35,0.13l-0.16,-0.76l-0.96,-0.44l-0.57,0.98l-0.71,-0.89l-0.02,-1.13l-0.56,0.11l-0.62,-0.36l-0.17,0.54l-0.64,0.3l-1.19,0.24l-0.84,-0.35l-1.25,0.54l0.04,1.08l-0.65,0.68l-0.74,0.08l-1.13,-0.46l-1.25,0.29l-1.1,-0.56l0.19,0.21l-0.77,0.89l-2.05,0.34l-0.34,0.81l0.58,0.75l0.02,0.69l-0.97,-0.84l-0.99,0.87l-0.22,1.28l0.22,0.76l-0.42,0.89l-0.64,-0.41l0.25,-1.34l-0.28,-0.56l-3.35,1.35l0.3,1.09l0.57,0.15l0.38,0.89l-0.06,1.04l-0.81,-0.05l0.32,0.55l-0.22,1.27l0.52,0.43l0.07,0.94l-0.07,-0.22l-0.51,1.1l-0.36,0.01l-0.24,0.47l-0.65,-0.15l-0.54,0.37l0.52,0.28h-0.57l0.24,0.37l-0.59,0.27l-0.43,-0.37l-0.28,0.52l-0.64,0.09l-0.15,0.2l0.56,0.48l0.41,-0.53l-0.14,0.69l-1.95,1.22l0.1,0.5l0.43,0.08l-0.5,0.15l-0.14,1.14l-0.63,0.57l1.47,-0.51l-1.06,1.16l-0.4,1.11l-0.74,0.45l0.73,0.12l-0.42,0.07l0.36,0.33l-0.54,0.3l0.57,0.45l-0.08,0.55l-0.47,0.17l0.1,0.74l-0.36,-0.02l0.69,1.06l-0.78,1.49l-0.5,-0.15l-0.15,0.37l-0.75,0.04l-0.2,0.36l-0.52,-0.11l-0.42,-0.91l-0.3,0.26l-0.59,-0.19l0.53,1.55l0.64,0.17l-0.12,0.6l0.51,0.36l-0.85,0.28l-0.08,-0.61l-0.43,-0.18l0.16,0.24l-0.33,0.05l0.35,0.3l-0.97,0.13l-0.05,0.88l0.67,0.41l0.03,1.04l0.86,0.29l0.16,0.74l-1.74,-0.73l-0.23,-1.37l-0.44,-0.36l-0.36,0.3l0.3,0.39l-0.15,0.36l-0.76,0.44l0.38,0.22l-0.15,0.38l-0.92,-0.09l-0.27,0.44l-0.44,-0.18l0.12,0.42l-0.4,0.03l-0.2,0.81l-1.1,-0.3l0.61,0.49l-0.34,0.21l0.42,0.5l-0.12,0.5l-1.16,0.65l-1.07,-0.25l0.3,0.89l-0.61,-0.28l0.02,0.92l-0.62,-0.01l-0.1,1.11l-0.41,0.28l0.15,0.82l-0.28,0.13l0.31,0.41l-1.47,1.22l-0.45,-0.13l-0.28,0.55l-0.09,3.23l-1.93,0.38l-0.54,-0.69l0.23,0.41l-0.44,1.41l0.42,0.64l-0.81,-1L139.1,483l0.45,-0.24l0.27,0.58l-0.45,0.15l-0.52,1.13l-1.82,1.15l-1.11,-0.38l-0.11,0.21l-0.19,-0.31l-0.11,0.38l-0.27,-0.32l-0.35,0.51l0.69,0.21l-0.35,0.2l0.03,0.56l0.88,1.29l-0.38,0.7l-0.43,-0.04l-0.05,0.34l-0.27,-0.18l0.19,0.48l0,0l1.45,1.04l0.54,-0.01l0.21,0.51l0.72,0.36l-0.12,1.49l0.7,-0.89l1.39,1.11l0.19,-0.4l0.53,0.24l0.1,-0.23l0.14,0.49l2.24,1.02l-0.16,0.58l1.86,0.42l2.61,1.55l0.45,4.76l2.46,4.77l1.31,0.49l0.07,1.27l0.91,2.85l1.16,1.03l4.51,1.72l4.31,10.71l1.88,2.9l4.22,2.67l2.11,1.82l6.95,9.28l0,0l1.5,-0.67l0.98,-2.37l0.9,-5.28l3.54,-2.76l7.54,5.77l1.65,0.61l5.22,0.3l2.09,0.87l1.39,0.98l2.72,3.87l3.25,0.77l4.56,-2.03l0,0l1.59,-3.05l0.22,-4.87l3.11,-1.64l-0.79,-7.53l-0.58,-0.31l0.48,-0.38l-0.2,-3.07l-0.59,-4.24l-0.69,-1.89l3.96,-3.39l-0.13,-0.49l1.02,-0.24l4.73,-4.2l-0.1,-1.16l0.66,-0.15l0.31,0.48l0.97,-0.9l-0.41,-0.71l0.67,0.5l2.45,-1.37l-0.45,-0.43l0.25,-0.28l0.63,0.52l6.16,-3.01l0,0l0,0l0,0l-2.89,-1.55l-0.37,-15.07l-1.74,-0.29l-0.81,-0.6l0.04,-2.58l-0.28,-0.38l-4.05,-0.37l-2.82,-2.5l-0.12,-0.77l0.64,-0.76l-0.5,-0.57l0.36,0.1l-0.23,-0.61l0.4,0.13l0.02,-0.89l-0.67,0.22l-1.08,-2.37l-4.27,-3.72l1.15,-1.4l-0.3,-0.55l0.83,-0.16l-0.21,-0.68l0.65,0.31l3.26,-3.88l2.77,0.45l-0.49,-1.22l0.76,-0.35l0.71,0.72l-0.07,-1.41l0.79,-1.71l1.68,-1.07l-0.06,-1l-0.57,-0.52l0.58,-0.55l0.32,0.43l0.85,-0.19l-0.67,0.66l0.79,1.01l0.29,-0.24l-0.49,-0.34l0.77,-0.42l-0.08,-0.28l0.76,-0.34l0.26,0.43l3.19,-1.31l0.65,-2.08l0.87,0.33l-0.09,-0.9l0.53,-0.15l-0.32,-0.46l0.05,-1.08l0.33,-0.07l0.15,-0.58l-0.48,-0.49l0.53,-1.82l7.59,-5.68l1.2,0.26l0.61,0.52l0.34,-0.22l4.49,1.22l0.72,-1.42l-0.46,-0.89l1,-0.26l0.3,-0.68l-1.04,-2.62l1.1,-2.76l-0.14,-0.64l-0.66,-0.45l0.5,-0.38l-0.27,-0.91l-1.62,-2.15l-0.43,-0.14l-1.88,-2.96l2.11,-4.79l3.96,0.27l3.74,-0.52l1.06,-0.99l2.07,-1.09l3.5,1.14l0.48,-0.83l-0.14,0.91l3.38,1.08l1.32,-5.98l0.32,0.13l-0.22,-0.53l0.8,0.52l-0.62,-0.43l0.6,-0.55l-0.09,-0.3l-0.62,0.41l0.25,-1.87l2.75,-2.6l7.37,-1.63l0.44,0.46l0.31,-0.58l5.82,-1.08l0.4,-0.75l0.35,0.15l-0.47,0.54l0.83,0.65l-0.46,-0.71l3.2,-0.6l0.66,-1.8l-0.2,-0.33l0.76,-3.19l0.86,-1.38l-0.27,-1.34l5.02,-2.19l-0.86,-0.22l0.52,-0.11l0,-0.4l0.34,-0.05l0.17,0.66l4.72,-2.11l2.76,0.78l3.3,-0.96l-0.78,-0.05l0.9,-0.92l0.92,0.22l-0.81,-0.38l0.96,-1l0.26,0.27l0.07,-0.66l0.82,-0.84l-0.14,-1.92l3.36,-0.2l5.81,2.46l0.72,-0.25l-0.02,-0.51l0.88,-0.51l5.11,0.94l1.38,-0.29l0,0l3.49,-4.89l-3.5,-3.78l-1.02,-2.15l9.37,-4.58l0.89,0.74l3.06,1.37l-2.3,-17.86l-1.4,-5.35L336.6,352.33z"},{id:"FI-15",title:"Northern Savonia",d:"M230.41,502.25L229.78,501.74L229.52,502.01L229.98,502.44L227.52,503.81L226.85,503.31L227.26,504.02L226.3,504.93L225.99,504.45L225.33,504.6L225.43,505.76L220.69,509.96L219.67,510.19L219.81,510.68L215.85,514.07L216.54,515.96L217.13,520.2L217.33,523.26L216.85,523.64L217.43,523.95L218.22,531.48L215.1,533.12L214.89,537.99L213.3,541.04L213.3,541.04L214.5,542.37L212.74,544.74L211.17,548.35L211.63,548.46L213.02,550.13L213.43,554.03L214.52,556.57L214.75,558.46L213.6,558.73L214.16,563.16L214.92,564.05L214.89,565.04L215.4,565.53L215.89,567.2L216.66,568.41L219.4,570.42L219.55,570.95L216.48,570.36L215.96,571.62L218.14,574.69L219.46,574.62L217.58,578.65L216.06,576.65L212.81,576.84L211.52,577.79L210.14,578.15L211.02,581.21L214.69,582.95L214.7,583.41L213.77,584.29L214.83,585.73L215.51,585.36L215.96,585.74L220.21,591.19L221.61,589.93L221.35,589.21L223.02,588.29L223.93,589.54L225,591.45L225.76,593.87L226.88,595.61L227,597.67L227.7,598.6L227.97,600.58L227.28,601.17L227.99,602.11L227.11,602.26L226.67,603.78L225.69,605.42L225.08,606.07L224.23,606.08L223.9,607.04L229.05,611.74L230.7,610.93L231.48,611.63L231.48,611.63L233.2,613.63L235.43,612.37L234.92,611.45L235.43,610.6L236.93,609.37L237.15,610.03L238.73,611.34L239.32,612.33L239.84,611.27L239.11,609.96L239.67,609.21L240.64,610.47L242.71,610.38L243.33,609.22L244.06,609.41L244.18,608.7L244.58,608.47L244.43,607.94L246.04,609.63L246.36,610.82L246.17,611.22L247.01,611.42L246.87,610.46L247.49,609.91L247.71,610.17L247.29,610.71L247.41,611.03L247.79,610.9L248.07,609.74L248.81,609.79L249.36,610.9L249.92,610.98L250.48,609.36L251.59,608.58L252.26,608.59L251.96,607.81L252.46,607.86L252.63,607.3L251.84,606.81L252.39,606.3L253.17,608.01L253.86,608.11L254.11,608.69L255.44,609.52L255.67,610.36L259,611.87L260.93,613.96L261.67,615.32L262.65,616.07L262.91,617.03L265.06,617.54L265.36,618.01L264.24,619.31L264.39,620.48L265.91,621.31L267.36,623.57L267.69,623.71L268.21,623.12L269.38,623.61L269.33,622.83L271.63,625.15L271.76,624.74L275.4,627.27L279.04,627.27L281.78,626.66L283.91,627.88L285.73,628.18L289.99,630.16L291.96,630.16L293.49,628.03L293.49,626.51L288.62,620.43L285.73,622.1L285.13,621.8L285.28,619.82L284.82,618.3L283.05,618.06L282.94,617.4L283.29,616.77L281.82,615.7L281.78,614.29L280.57,613.56L280.78,612.98L282.22,612.29L282.27,611.52L281.58,610.82L282.01,610L282.5,610.38L283.13,610.23L284.16,611.02L284.96,610.95L285.26,609.33L284.48,608.11L284.72,607.61L285.08,607.71L285.78,605.97L285.45,604.47L285.92,603.63L285.57,603.14L286.97,603.39L287.64,603.86L287.9,603.7L289.37,604.94L290.11,603.56L287.83,602.35L289.87,602.44L290.64,601.6L291.21,602.73L292.02,602.19L292.73,600.97L291.86,600.65L292.97,599.91L293.66,597.38L293.66,597.38L293.74,596.54L295.17,594.88L293.29,592.32L292.99,591.36L293.3,590.28L294.51,589.11L295.7,589.29L296.67,587.54L296.57,586.59L297.53,585.47L298.05,585.11L299.33,585.69L299.89,586.88L301.55,587.76L302.54,589.33L302.89,589.23L303.71,587.19L307.85,584.27L305.08,582.33L305.13,581.73L304.76,581.8L303.66,579.77L302.74,579.15L302.5,577.94L303.5,578.73L304.55,578.54L304.18,577.81L304.46,577.88L304.42,577.59L303.51,577.26L303.84,576.35L306.86,574.53L305.92,572.68L302.25,570.85L301.9,570.28L300.47,569.51L299.25,566.74L295.4,561.43L295.09,560.52L292.33,559.05L293.88,556.44L293.55,555.72L294.38,555.33L294.53,554.69L295.36,554.21L295.24,553.35L294.72,553.34L295.62,552.73L295.42,552.32L296.31,551.43L297.03,546.07L294.02,543.5L293.54,540.31L292.07,536.08L292.36,535.14L293.03,534.62L293.56,535.1L294.6,534.21L294.18,533.68L293.77,533.83L292.73,533.34L292.38,533.04L292.5,532.6L292.15,532.58L291.52,526.62L292.13,525.46L291.5,524.54L290.38,523.62L288.35,524.09L287.51,523.75L286.36,521.79L284.25,519.64L284.25,519.64L281.5,525.84L279.47,523.14L277.34,521.8L274.68,517.75L270.01,512.76L269.31,512.87L264.61,508.6L262.05,507.51L261.54,507.78L258.04,505.04L256.14,504.75L256.62,505.53L255.11,505.91L254.06,505.05L254.3,504.54L254.09,504.35L248.98,502.6L245.02,502.07L244.61,502.51L241.31,501.96L236.57,499.24z"},{id:"FI-16",title:"Päijänne Tavastia",d:"M175.9,679.69L179.31,678.55L179.19,677.91L179.77,678.26L180.63,678.18L181.43,679.02L182.72,677.77L184.92,678.13L185.6,677.66L190.75,677.19L192.99,667.54L192.79,664.52L193.87,664.3L194.93,664.72L196.27,664.25L198.13,661.81L198.76,661.72L200.78,662.63L201.05,663L200.61,663.51L201.44,663.94L203.49,658.15L204.16,657.58L203.91,656.14L205.03,656.59L204.32,658.78L205.81,658.52L206.3,656.95L206.47,657.48L208.25,658.94L208.56,660.86L209.25,661.49L210.22,661.27L210.48,660.34L210.9,661.12L210.81,661.83L211.38,662.29L211.28,665.04L213.37,668.23L214.22,668.38L214.93,666.33L216.07,666.91L217.32,666.86L217.86,665.87L218.06,666.32L218.4,666.07L218.82,667.02L218.41,667.89L218.87,669.08L218.87,669.08L218.97,671.44L218.5,671.08L217.15,671L217.91,671.81L217.86,672.86L218.03,673.36L218.37,673.41L218.15,674.7L217.39,674.9L217.64,675.9L218.72,676L219,674.8L219.21,675.78L219.69,675.64L219.93,676.11L217.22,675.98L218.14,678.55L216.54,679.89L217.24,681.28L218.99,683.14L217.86,684.82L217.95,685.2L218.96,684.99L218.96,685.85L221.62,688.23L221.62,688.23L221.85,688L223.71,688.17L223.71,688.17L224.13,688.24L224.6,689.23L225.08,691.59L225.08,691.59L223.04,692.32L222.48,692.91L222.46,694.01L221.49,695.36L221.04,697.16L219.65,698.26L217.3,698.81L217.31,699.72L216.28,700.93L213.56,700.51L213.19,699.33L212.08,700.3L210.24,703.22L212.19,704.46L212.05,706.36L212.52,706.54L212.99,707.74L212.47,710.54L211.15,711.42L210.73,711.07L210.77,710.58L210.32,710.69L210.12,711.36L210.7,713.67L214.22,714.22L212.76,716.33L212.44,717.24L212.68,718.1L211.76,718.71L211.28,720.33L211.91,720.77L212.75,720.59L215.22,722.49L215.52,725.47L215.52,725.47L215.97,727.29L215.68,728.14L213.37,729.81L212.32,730.11L209.72,728.15L206.71,728.85L206.09,726.86L204.29,727.14L203.49,728.23L201.72,728.58L200.7,728.66L199.91,728L198.52,729.75L197.5,729.67L197.51,730.48L196.46,730.6L196.35,731.04L193.46,728.92L193.46,728.92L193.46,728.92L193.46,728.92L193.64,727.83L193.32,726.32L192,723.12L190.76,722.95L189.02,725.76L187.09,725.28L186.41,725.84L185.94,724.16L183.93,722.44L183.51,720.04L182.9,720.43L182.77,721.49L180.31,721.7L180.31,721.7L180.19,721.21L179.74,721.18L179.33,720.06L179.73,718.52L180.32,718.47L179.83,714.94L178.33,714.34L177.09,714.26L177.61,712.13L178.72,710.38L178.43,710.21L178.57,709.71L177.69,709.82L178.3,708.29L177.67,707.54L178.67,706.27L181.67,705.38L182.22,704.69L183.17,704.51L183.74,702.63L185.1,701.08L184.42,700.23L185.46,699.2L184.86,697.92L185.16,697.24L184.99,696.63L184.39,696.37L183.22,694.85L183.27,693.68L180.22,692.71L177.75,693.25L177.22,690.42L175.87,691.44L175.21,690.44L174.38,690.9L173.98,688.13L173.98,688.13L173.22,686.13L173.72,684L173.4,683.61L173.92,682.05L172.69,680.59L172.06,677.93z"},{id:"FI-17",title:"Satakunta",d:"M62.16,695.51l1.61,1.16l-1.12,0.04l-0.91,-1.18L62.16,695.51zM60.53,695.28l0.95,0.14l0.25,0.38l-0.33,-0.08l-0.35,0.62l0.87,0.96l-0.23,0.39l-0.66,-0.18l-0.42,0.66l-0.86,-0.34l0.25,-0.66l-0.52,-0.4l1.07,-0.53L60.53,695.28zM63.55,693.19l1.07,-0.08l0.28,0.54l0.53,0.05l0.26,0.28l-0.42,0.42l0.26,0.56l-0.73,0.13l-0.53,-0.62l-0.68,-0.06l0.24,-0.25l-0.25,-0.26l-1.06,0.15l0.24,-0.29l-0.43,-0.38l0.6,-0.36L63.55,693.19zM64.29,666.77l0.88,0.04l0.05,0.41l0.42,0.1l-0.05,0.66l-0.58,-0.28l0.17,0.6l-1.37,-0.24l-0.32,0.27l-1.15,-0.75l-0.03,0.52l0.99,0.81l-0.05,0.74l-1.2,-1.36l0.03,-0.68l-0.19,0.2l-0.33,-0.28l-0.19,0.29l-0.33,-0.37l0.15,-0.36l0.51,0.14l0.29,-0.37l1.29,0.93l0.63,0.06l-0.09,-0.54l0.37,-0.11l-0.29,-0.44L64.29,666.77zM107.46,624.15l-0.33,2.18l0.69,0.27l0.31,2.49l-0.41,0.71l0.65,1.16l-2.85,1.09l-0.2,0.93l0.51,5.57l-1.92,0.57l-1.14,-0.09l-2.58,1.15l-2.17,2.74l1.21,0.91l0.9,0.13l-0.09,1l0.27,0.04l0.23,-0.69l-0.08,-0.67l0.45,0.31l-0.13,0.88l1.11,0.21l0.05,0.67l-0.31,0.27l0.62,1.46l0.64,0.61h1.01l0.66,0.71l-0.15,1.41l1.54,0.59l0.15,0.7l-1.62,0.71l0.34,0.78l0.64,-0.41l1.93,2.6l-0.18,1.15l-0.44,0.22l0.21,0.36l-0.36,1.38l-0.58,1.01l-0.65,-0.17l-1.18,0.53l0.13,0.45l-0.47,0.42l-0.4,-0.12l-0.84,0.93l0.24,1.77l-1.27,0.16l0.21,0.91l0.77,0.77l-0.93,0.26l0.19,0.87l1,-0.43l0.13,-0.92l0.32,-0.05l0.1,0.31l0.4,-0.07l-0.13,1.14l0.43,0.69l-0.69,1.42l-1.36,-1.19l1.12,2.76l-1.66,1.11l-0.11,1.4l-1.25,1.31l-0.62,-0.34l2.36,4.68l0.44,0.33l0.24,-0.31l1.44,0.1l0.2,1.01l-0.49,0.16l0.57,1.72l-2.07,0.49l0.34,1.44l-0.4,-0.73l-0.06,0.79l-0.43,-0.2l-0.63,0.29l0.22,1.11l-2.02,-0.78l-0.47,0.2l1.02,3.46l-1.03,0.76l1.67,2.07l1.09,3.53l1.81,0.05l0.17,0.34l0.13,-0.36l1.88,0.02l2.4,1.09l0.38,-0.4l3.96,2.9l2.12,-0.14l0.26,0.82l0.45,-0.19l-0.35,-0.85l1.53,0.02l2,-1.01l2.01,0.29l0.35,-0.98l1,0.19l-0.4,2.49l3.87,3.47l-3.57,1.38l-0.2,-0.46l-0.75,-0.05l-0.37,0.59l0.76,0.39l0.02,1.08l1.11,0.44l-1.82,0.52l0.08,0.36l1.72,0.55l-0.87,2.49l0,0l0.17,0.86l-1.58,-0.07l-0.55,0.4l0,0l-1.04,-0.25l-0.56,-1.67l-3,-0.07l-1.27,0.6l-1.45,-1.35l-1.1,-0.03l-0.29,-0.74l-0.4,0.18l-1.03,-0.47l-0.46,-1.67l-1.41,-1.13l-0.25,1.45l0.67,1.03l-0.43,0.74l0.1,0.48l-0.61,0.23l0.6,1.69l-0.43,1.41l-0.61,-0.39l-2.61,1.24l-0.44,-0.32l-3.8,-0.25l-1.77,0.93l1.89,2.42l-2.07,-0.74L92.41,714l-1.49,1.11l-1.68,-0.75l-0.98,0.39l-1.4,1.27l0.93,0.43l-0.08,0.26l-0.81,-0.34l-0.62,1.29l-0.39,0.18l-0.97,-1.95l-3.68,0.2l-0.37,0.27l-0.49,-0.26l0.34,-0.71l-1.58,-2.21l0.1,-2.17l-0.86,-0.03l-0.63,-0.57l-0.68,0.22l-1.3,-1.64l-1.24,-0.72l0.63,-0.93l-1.52,0.01l-0.72,0.51l0.41,0.86l-0.95,0.78l-0.62,0.24l-0.57,-0.41l-1.06,0.59l-1.43,-3.6l-0.38,1.08l0,0l-0.55,0.3l-0.82,1.35l0,0l-2.38,0.43l0,0l-1.72,-1.41l-0.57,-1.62l0.57,-1.35l-0.51,0.11l-0.25,-0.53l-1.11,-0.41l-0.32,-0.62l0.62,-0.19l0.71,0.63l0.82,-0.36l0.64,0.38l0.57,-0.5l-0.82,-0.36l0.28,-0.56l-0.35,-0.05L63,702.11l0.44,-0.27v-0.47l-1.06,-0.62l1.35,-0.44l-0.1,-0.7l-0.99,-0.95l0.26,-0.42l0.41,0.23l0.22,-0.21l-0.4,-0.35l0.18,-0.74l-0.45,-0.39l1.6,-0.25l1.61,0.73l-1.05,-0.95l0.35,-0.72l-0.38,-0.36l0.61,-0.16l0,-0.72l0.66,-0.19l1.71,1.36l0.15,-0.34l-0.51,-0.46l0.88,-0.27l-3.89,-2.33l-0.13,-1.25l0.88,-0.16l-0.15,-0.91l-0.61,-0.42l0.78,-0.61l0.4,0.81l0.86,0.4l-0.33,-0.8l-0.79,-0.59l0.78,-0.49l0.71,-1.66l-1.46,-0.62l0.57,0.05l-0.25,-0.36l0.48,-0.33l-1.16,-0.61l-0.14,-0.39l1.2,0.2l-0.25,-0.49l0.99,0.27l-0.84,-0.67l-0.09,-0.59l-0.79,-0.81l-0.58,-0.06L63.2,681l0.31,-0.8l2.67,1l0.44,-0.35l0.27,0.55l0.34,-0.47l0.35,0.2l0.47,-1.13l-2.22,-2.6l-0.35,0.42l-1.55,-1.85l-0.64,-0.25l0.64,-0.19l0.57,0.37l0.4,-0.27l1.4,0.7l0.5,-0.07l0.5,0.49l1.86,-0.84l-0.06,-0.52l-1.48,-1.02l0.44,-0.46l-0.38,0.16l-0.12,-0.48l-0.44,0.15l0.32,0.37l-0.19,0.31l-1.1,0.25l-0.75,-2.89l-0.52,-0.25l-0.63,0.34l0.3,-0.62l-0.23,-0.39l0.46,-0.29l-0.17,-0.29l-0.67,0.24l0.08,-0.67l1.69,-0.32l0.46,1.16l1.4,0.85l0.95,-0.1l0.04,0.52l1.18,0.78l2,0.01l-1.06,-1.22l-0.89,-0.34l0.19,-0.28l-0.27,-0.29l-0.38,0.05l-0.18,-0.34l0.44,0.03l-0.51,-0.6l-0.61,-0.21l0.5,-0.14l-0.61,-0.51l0.04,-1.45l-0.31,0.28l-0.5,-0.98l-0.03,-1.07l-1.01,-0.16l-0.09,-0.69l0.33,-0.05l-0.83,-0.65l-0.3,-0.87l0.95,0.21l-0.72,-0.56l-0.88,-1.62l0.29,-0.06l0.72,0.85l0.43,-0.77l-0.09,-0.34l-0.28,0.12l0.18,-0.4l0.97,0.26l-0.77,-1.67l-0.9,-0.58l-0.64,-0.78l0.28,-0.1l-0.59,-0.34l0.17,0.93l-0.83,-0.31l0.09,-0.47l-0.72,-0.19l-0.24,-0.48l0.04,-0.68l-0.56,-0.56l-0.27,0.09l0.34,-0.28l0.69,0.36l0.09,-0.43l0.43,0.36l0.51,-0.24l0.41,1.01l-0.4,0.58l0.62,0.07l-0.04,-0.61l0.33,-0.03l-0.17,-0.91l0.24,0.05l-0.03,-0.89l0.28,-0.25l-1.83,-0.91l0.47,0.1l-0.48,-0.65l0.48,0.08l0.13,-0.28l-0.18,-0.55l-0.31,0.41l-0.22,-1.04l0.2,0.09l0.18,-0.6l-0.38,-1.14l-1.13,-1.57l0.38,-1.02l-1.24,-0.84l0.62,-1.02l-0.68,-0.17l-0.04,0.63l-0.38,-0.07l-0.36,0.8l-0.8,-0.25l-0.27,-1.05l-0.28,-0.01l0,0l1.62,-1.31l1.47,-2.22l3.05,-1.11l4.03,0.37l0,0l1.95,-0.06l8.51,2.78l4.31,-3.5l2.82,-4.76l4.09,-0.21l3.86,-6.4l1.86,-0.99l0.59,0.16l2.17,-6.8l5.06,2.55L107.46,624.15z"},{id:"FI-18",title:"Uusimaa",d:"M203.97,756.63l-0.05,0.72l-0.58,0.39l-1.21,-0.1l0.1,1.47l-0.3,0.12l-0.71,-0.86l-0.25,0.38l-0.93,-1.13l-0.42,-0.03l-0.21,-1l-1.09,0.15l-0.31,-0.32l-0.29,-1.62l-0.43,-0.19l0.04,-0.92l-0.42,-0.3l2.51,-0.33l0.31,0.72l1.35,0.63l0.85,1.96l0.89,0.34l0.89,-0.32L203.97,756.63zM209.15,753.79l-0.67,-0.48l0.32,-0.47l-0.6,-0.47l-0.43,0.12l-1,-0.91l-0.29,0.96l0.93,1.47l0,0.89l-0.7,0.21l0.17,2.15l1.36,-0.52l0.54,-0.68l0.31,0.63l0.54,-0.11l0.4,-0.53l-0.84,-0.35L209.15,753.79zM197.62,757.53l-0.05,-0.71l-0.51,-0.17l0.13,-0.3l-0.62,-0.05l-0.29,-0.81l0.34,-0.56l-0.52,-0.82l-0.88,0.85l-0.14,2.59l0.49,1.06l0.92,0.75l-0.7,0.6l0.7,0.9l0.33,-0.03l0.01,0.67l0.54,-0.41l-0.11,-1.29l0.72,0.03l0.11,-0.68l0.39,0.02l-0.13,-1.39L197.62,757.53zM215.52,725.47l0.63,0.61l0.76,-0.01l0.07,-0.8l0.46,-0.05l1,0.85l-0.03,1.17l0.96,1.11l-0.16,1.16l0.43,1.27l0.76,0.54l-0.45,0.45l2.62,0.72l0.75,0.56l0.92,1.78l0.06,1.05l1.8,0.16l0.15,1.17l0.72,-1.99l0.9,-1.35l0.12,-0.92l1.5,-0.59l1.18,0.16l1.98,4.16l0.28,0.62l-1.84,-0.85l-1.31,-1.64l-2.01,0.43l-1.42,2.12l-0.17,1.31l-1.06,0.07l-0.65,0.67l0.68,1.12l-1.3,0.84l-0.11,1.21l-0.32,0.34l0,0l-0.27,-0.11l-0.18,0.97l0.36,0.64l-0.42,0.06l0.52,0.83l-0.12,2.39l-0.32,0.23l-0.75,-0.21l-0.08,-0.76l-0.51,-0.01l0.57,2.81l-1,-1.19l0.11,-0.29l-0.77,-0.07l0.18,0.72l-0.75,-0.45l-0.58,0.45l0.58,0.9l-0.47,0.06l-0.03,0.72l-0.61,-0.11l-0.78,-2.11l0.28,-0.75l-0.58,-0.29l0.18,-0.47l-1.15,-1.14l-0.34,-0.89l-0.19,0.38l0.81,2.81l-0.28,0.19l0.56,0.59l-0.02,0.52l-1.4,-0.3l-0.04,-0.64l-0.5,0.12l-0.75,-0.49l-0.45,-0.8l0.2,1.67l0.61,0.02l0.09,0.36l-0.42,0.99l0.59,-0.17l0.06,1.07l-1.22,-0.48l-0.47,-0.62l0.32,-0.45l-0.37,-0.47l-1.88,-1.26l0.01,-0.56l-0.72,-0.79l-0.44,0.74l-2.84,-3.25l-0.37,0.42l0.1,1.35l1.12,-0.23l0.18,1.23l1.35,1.11l-0.83,1.72l0.85,0.42l1.24,2.1l0.68,0.05l0.25,1.35l-0.89,1.33l-2.09,-0.05l0.43,-0.76l-0.59,-1.7l-0.29,0.17l-0.43,-0.75l-1.52,-0.27l-0.24,-0.74l-0.94,-0.43l-0.41,-1.55l-0.91,-0.77l-0.92,-0.21l1.57,1.69l1.05,2.43l-0.02,0.44l-1.7,1.18l0.56,1.11l0.64,0.32l-0.15,0.42l-0.41,0.07l0.19,0.84l0.42,-0.07l0.22,0.29l-0.25,0.41l0.86,0.63l-0.03,0.6l-0.87,0.45l-0.47,0.17l-0.71,-1.26l-0.21,-1.68l-1.4,0.35l-1.82,-2.36l-0.49,-0.18l-0.15,0.51l-1.55,-1.55l-1.44,0.29l-0.06,-1.14l0.68,-0.07l0.05,-0.42l1.4,1.14l0.31,-0.68l-0.83,-0.39l0.43,-0.68l-0.52,-0.57l-0.11,0.25l-0.7,-0.08l-1.55,2.24l0.24,0.06l-0.19,0.65l-0.47,-0.02l-0.67,0.91l-0.38,-1.15l-1.42,0.31l-0.3,-0.29l-0.04,0.5l1.01,0.36l0.26,0.72l-0.61,1.75l-0.77,0.71l-0.54,1.43l-0.69,-0.41l-0.94,0.27l-2.02,-0.14l0.24,-1.02l-0.44,-0.03l-0.81,0.37l-0.14,0.43l-3.2,0.3l-0.92,0.48l-0.21,0.76l-0.73,-0.25l0.06,1.7l-0.35,0.23l0.32,0.32l-0.29,0.33l-0.32,0.28l-0.2,-0.61l-0.88,0.16l0.64,1.03l-1.8,-1.1l-0.94,0.15l-0.02,0.74l-0.64,-0.15l-1.23,0.6l-0.26,-1.14l0.77,-0.1l-0.19,-0.97l-0.5,-0.09l-0.66,2l-0.81,0.42l0.16,1.46l-0.89,0.02l-0.36,0.43l-0.61,-0.46l-0.12,-0.55l0.28,-1.15l-0.22,-0.34l-0.91,-0.06l-0.95,-1.45l-0.15,0.4l-0.73,0.31v0.55l0.77,-0.01l-0.2,1.41l1.8,0.01l0.01,1.48l-0.63,0.03l0.06,-0.53l-0.52,0.08l-0.14,-0.68l-1.25,-0.31l-0.28,0.51l-1.58,0.58l-0.17,0.4l-0.92,-0.17l-1.16,0.53l0.92,0.54l0.43,-0.31l0.24,0.56l-0.72,0.22l-0.75,-0.33l-0.36,0.42l0.3,0.23l-0.39,0.1l-0.66,-1.58l-0.4,0.24l-0.27,-0.93l-0.62,-0.22l0.35,1.4l-0.46,0.89l0.72,0.31l0.24,-0.43l0.32,0.98l-0.28,0.8l-3.25,3.26l0.28,0.85l-0.59,0.5l-0.7,0.08l-0.13,1.13l-2.04,1.18l-0.21,0.44l-0.61,-0.14l-0.68,0.88v-0.95l0.99,-0.68l0.35,-1l-0.33,-0.08l1.23,-1.59l-0.61,0.18l-0.07,-0.84l-0.65,0.82l-0.21,-0.28l-0.3,1.08l-0.74,0.08l-0.07,-0.75l-0.77,0.04l-0.43,0.98l0.26,0.26l-0.99,0.32l-0.01,-0.72l1.31,-1.44l-0.04,-0.83l0.54,-0.6l-0.2,0.08l0.15,-1.53l-0.82,-0.59l-0.37,0.14l-0.21,0.7l-0.37,-0.01l0.17,-0.24l-0.58,-0.35l-0.45,0.66l0.8,1.16l-0.49,0.24l-0.68,-0.22l-0.54,0.86l-0.61,0.17l-0.79,-0.95l0.08,0.71l-0.39,-0.08l-0.1,-0.72l-1.16,0.08l-0.32,0.56l1.02,0.57l0.26,0.82l-1.17,0.15l-0.52,-0.26l0.13,-0.31l-0.54,-0.17l0.01,-0.52l0.47,-0.1l0.06,-0.42l-1.08,0.78l0.3,0.52l-0.31,-0.03l-0.13,0.43l-0.37,-0.43l-1.07,0.06l0.64,0.38l0,0.37l-1.92,-0.36l-0.21,-0.77l0.52,-0.52l-0.81,-0.01l-0.48,0.5l0,0.5l-1.27,1.26l-2.95,-0.52l2.19,0.86l-0.11,0.83l-0.4,-0.35l-1.28,0.14l0.53,-1l-1.3,0.42l-1.03,1.93l-1.44,0.51l-0.06,-0.31l0.52,-0.03l-0.4,-1.02l-0.61,0.33l-0.4,-0.31l-0.88,0.05l0.86,0.36v0.56l-0.39,0.23l0.17,0.61l-0.49,-0.03l-0.52,-0.91l-0.29,0.1l0.9,1.84l-0.78,-0.27l-1.03,0.73l-1.82,-0.31l-0.95,0.42l-1.44,-0.2l-2.57,0.83l-0.3,0.41l-1.25,0.11l-1.05,-1.23l0.38,-0.5l1.1,-0.67l0.94,0.7l0.23,-0.13l-0.21,-1.01l2.49,-1.37l-1.75,0.08l-0.25,0.71l-1.46,0.47l0.18,-0.83l-0.51,-0.3l-0.9,1.35l-0.41,1.35l-1.88,1.04l-0.38,0.69l-1.19,0.76l-1.32,0.52l0.17,1.63l0.47,0.17l-0.37,0.81l0.51,0.5l-1,0.03l-1.27,0.77l-0.47,-0.46l-0.55,0.55l-1.04,0.11l-0.73,-0.56l-0.36,0.65l-0.73,-0.27l0.21,0.52l-0.52,-0.36l-1.25,0.29l-0.36,-0.25l-1.43,0.57l-0.58,-0.38l-0.89,0.87l-0.41,0.01l0.24,-0.95l0.71,-0.3l-0.03,-0.5l0.32,0.08l-0.03,-0.58l0.44,-0.13l0.22,0.29l0.42,-0.51l0.59,0.22l1.4,-1.25l1.33,-0.3l0.29,-0.73l0.81,-0.08l0.01,-0.27l1.79,0.04l0.38,-0.36l-0.21,-1.6l-0.62,-0.3l0.29,-0.89l0.99,-0.36l0.84,-1.1l-0.59,-1.1l-0.53,0.43l0.11,0.77l0.32,0.17l-0.26,0.54l-0.77,0.11l0.02,-0.44l0.31,0.19l-0.04,-0.55l-0.65,-0.51l-0.45,0.31l0.04,0.91l-0.75,0.33l-0.41,-0.35l0.29,-2.28l0.36,-1.12l2.56,-0.85l0.65,-1.11l-0.49,-0.13l-0.77,1.1l-2.47,0.8l-1.16,0.99l-0.9,0.06l-0.17,0.49l1.39,-0.29l0.12,0.38l-0.69,1.85l0.4,0.76l-0.03,0.94l-0.67,0.39l-0.35,-0.16l-0.22,0.54l-0.05,-0.76l-0.37,-0.08l-0.38,-0.76l-0.56,-0.12l-0.27,-1.05l-0.43,1.36l0.49,-0.17l0.51,0.27l0.4,1.07l-0.75,-0.8l-0.37,0.59l-0.47,-0.17l-0.54,0.75l-1.73,-0.49l-1.15,-1.7l0.52,-0.62l-0.41,-0.55l-0.8,-0.24l-0.24,-0.89l-0.3,-0.07l-0.16,-2.36l1.05,-0.35l0.12,0.45l-0.32,0.14l0.22,0.4l-0.27,0.01l0.14,0.92l0.44,0.11l-0.38,0.43l0.41,0.15l-0.02,0.98l0.8,-0.85l0.6,-0.06l0.38,0.46l0.16,-1.22l1.2,0.03l-0.03,0.77l0.56,-0.02l0.45,0.59l0.84,-0.56l-0.14,-0.4l0.64,-0.29l0.11,-0.75l-0.62,-0.16l-0.02,-0.84l-0.69,-0.95l0.32,-0.49l0.95,-0.54l2.65,0.77l0.29,-0.49l1.31,-0.46l0.16,-0.61l0.53,-0.21l1.76,0.31l-0.78,1.2l0.3,0.27l0.54,-1.09l0.92,-0.51l-1.01,-0.07l-0.22,-0.4l-2.53,0.04l-1.49,0.97l0.29,0.44l-0.19,0.46l-0.83,-0.5l-0.57,0.24l-0.26,-0.4l0.57,-0.29l-0.66,-0.1l-0.08,-0.6l-0.47,-0.38l-0.51,0.56l-0.51,-0.06l-0.36,-0.48l-0.12,-0.94l1.06,-0.06l0.01,-0.33l-0.57,-0.24l0.78,-0.35l0,0l0.94,0.87l0.41,-0.52l2.57,-0.35l1.51,-1.38l-0.01,-0.7l0.63,-0.05l2.06,-1.26l0.14,-1.44l0.75,-0.77l0.62,0.04l-0.31,0.98l1.51,1.41l0.53,-1.06l1.16,0.12l1.58,-0.42l2.76,-1.95l1.07,0.13l0.83,0.54l1.16,-0.67l-0.51,-2.02l0.38,-0.22l-1.93,-1.34l0.3,-0.37l0.56,0.12l0.12,-0.64l0.35,0.71l0.05,-1.39l0.51,-0.1l0.93,-1.24l0.51,0.57l1.23,-0.88l0.23,-1.97l-0.36,-2.01l0.67,-0.13l0.91,-1l0.48,-0.01l0.16,-2.77l-0.29,-1.33l-2.84,-0.02l1.32,-2.6l2.58,-0.28l0.7,0.2l0.86,-0.88l-0.02,-1.02l-0.5,-0.66l0.44,-0.56l-0.6,-1.12l1.35,-0.14l0,-0.94l0.98,-1.83l-0.02,-0.38l-1.59,-0.77l1.03,-2l0,0l0.63,-0.27l1.64,1.03l2.29,-0.4l1.4,1.05l1.55,0.32l1.36,-0.29l1.92,0.65l-0.06,1.18l1.62,2.17l0.59,-0.3l-0.31,-0.9l1.74,-1.77l1.93,1.25l-0.33,0.92l0.81,1.67l3.95,-0.45l0.89,-1.68l-0.41,-1.01l0.11,-2.3l1.53,-1.99l2.46,1.16l1.53,0.12l0.86,-0.74l0.94,0.26l0.44,-1.05l0.73,0.31l0.03,0.47l1.92,0.01l0.11,-0.28l0.74,0.01l0.5,-0.7l3.2,-0.72l0.86,1.04l1.57,0.48l-0.81,-2.42l3.43,-1.69l-1.5,-0.48l-0.85,-0.97l-1.68,2.08l-0.24,-0.72l1.02,-2.42l1.99,-0.41l0.04,-0.64l-1.59,-1.95l0.14,-0.41l0,0l2.46,-0.2l0.12,-1.06l0.61,-0.39l0.43,2.4l2.01,1.73l0.47,1.68l0.68,-0.56l1.92,0.48l1.74,-2.8l1.24,0.16l1.32,3.2l0.32,1.51l-0.18,1.09l2.88,2.12l0.11,-0.44l1.05,-0.12l-0.02,-0.8l1.03,0.07l1.38,-1.75l0.8,0.67l1.01,-0.08l1.78,-0.36l0.79,-1.09l1.8,-0.27l0.62,1.98l3.01,-0.69l2.61,1.96l1.05,-0.3l2.31,-1.67l0.3,-0.86L215.52,725.47z"},{id:"FI-19",title:"Finland Proper",d:"M92.66,776.9l0.1,0.71l-0.93,1.12l-0.43,-1.04l0.19,-0.85l0.9,0.09l0.14,-0.33L92.66,776.9zM94.66,776.03l-0.22,2.98l-0.59,0.44l-0.42,-1.73l1.04,-2.16L94.66,776.03zM97.59,775.24l1.11,0.28l0.06,0.7l-1.6,0.87l-0.24,-1.56L97.59,775.24zM100.65,775.06l0.8,1.1l-0.22,0.22l0.35,0.36l-0.26,0.19l-1.16,-0.61l-0.07,-0.72L100.65,775.06zM110.13,770.02l0.65,0.14l-0.65,0.44l0.09,1.13l-1.12,0.72l0.51,0.34l-0.66,0.49l0.31,0.65l-0.88,0.25l-0.2,-2.56l0.69,0.21l0.46,-0.38l-0.12,-0.3l-1.23,-0.21l1.2,-0.88l0.59,0.23l0.11,-0.47L110.13,770.02zM110.54,766.46l1.25,0.33l-0.29,0.62l0.33,0.16l0.07,1.09l-0.47,0.46l-0.9,-0.44l-0.51,0.67l-0.72,0.05l-0.21,-0.41l-1.37,0.37l0.35,-0.53l0.6,0.18l-0.08,-0.99l0.69,-1.21L110.54,766.46zM79.91,766.08l1.1,0.13l0.47,0.56l-1.54,0.56l-0.94,-0.18l-0.02,-0.51l-0.65,-0.23l0.12,-0.33l1.52,-0.66L79.91,766.08zM68.21,762.46l1.5,0.57l1.34,0.02l-0.1,1.37l-0.72,0.56l-0.8,-0.01l0.06,0.43l0.34,-0.22l0.21,0.32l0.27,1.27l-0.74,0.44l-2.01,0.26l-2.05,-0.19l0.06,-0.47l-0.69,-0.53l0.44,-0.78l-0.23,-0.25l0.22,-0.78l0.98,-0.44l-0.28,-0.22l0.96,-1.03L68.21,762.46zM93.25,761.01l-0.06,0.85l-0.3,0.17l0.17,0.44l-0.54,1.11l-0.49,-0.12l-0.32,0.42l-0.05,1.06l-1.27,-0.02l-0.25,0.28l-0.15,-0.49l0.36,-0.53l-0.29,-0.47l0.67,-1.63l0.43,0.06l1.25,-0.96L93.25,761.01zM84.12,760.24l0.08,1.5l-0.95,0.61l-1.27,-0.01l1.03,0.63l-0.02,0.92l-0.77,-0.03l0.44,0.46l-1.83,0.64l-0.27,-0.56l0.2,-0.49l-0.58,-0.17l0.17,0.34l-0.37,0.82l-1.05,-1.1l0.28,-0.66l0.4,-0.01l-0.19,-1.1l1.64,-0.57l0.45,0.28l0.92,-1.25l1.52,-0.45L84.12,760.24zM69.32,758.18l-0.43,0.54l0.2,0.42l-0.98,0.22l0.28,0.81L67.48,760l-0.7,0.53l0.34,-2.24L69.32,758.18zM90.66,757l-0.06,0.99l0.7,1.33l-1.63,2.35l-1.49,0.33l-0.31,0.39l-0.34,-0.55l-0.5,0.15l0.24,-0.67l-0.4,-0.05l0.62,-0.69l0.69,-1.87l-0.5,0.32l-1.28,-0.1l-0.18,0.55l-0.81,0.33l-0.08,-0.37l-0.99,-0.12l0.71,-0.65l1.45,0.08l0.48,-0.38l1.27,0.19l1.1,-1.08L90.66,757zM95.65,754.63l0.22,0.71l-0.69,0.26l0.06,0.63l-0.86,0.95l-0.05,1.23l-2.93,0.8l-0.58,-1.92l1.58,-0.93l0.23,-0.91L95.65,754.63zM78.57,754.34l1.09,-0.03l0.78,0.39l-0.46,0.43l0.01,0.87l-0.62,0.11l0.15,0.53l-1.49,-0.12l-0.99,-0.64l0.21,-0.97l-0.52,-0.35L78.57,754.34zM111.63,754.38l0.69,0.75l-1.5,2.63l-1.29,1.36l0.01,1.04l-1.13,0.28l-0.28,1.32l0.49,0.72l-1.08,0.43l-0.14,0.39l0.87,0.38l-0.34,0.38l0.67,0.68l-0.35,0.66l0.77,0.28l-0.74,0.58l-0.54,2.08l-2.21,1.19l0.27,1.83l-0.31,0.14l-0.1,-0.31l-0.37,0.51l1.09,0.37l-0.16,1.26l-0.67,0.36l-0.21,-0.61l-0.39,0.49l-0.55,-0.15l-1.03,0.6l-0.63,-1.76l0.31,-0.57l-0.49,-0.4l-0.42,1.89l-1.09,0.23l0.14,-0.27l-0.54,-0.43l-0.71,0.42l-0.59,-0.7l-0.71,0.03l-2.29,1.39l-0.43,-0.36l0.04,0.59l-0.36,0.38l-0.65,-0.4l0.12,-0.45l0.26,0.08l-0.27,-1.3l-0.24,-0.09l0.11,0.77l-0.64,0.79l-0.3,-0.29l0.08,-1.17l-0.43,-0.08l0.32,1.67l-0.4,0.39l-0.51,-1.41l0.27,-1.02l-0.65,-1.44l0.08,-1.87l0.79,-0.15l0.7,-1.11l0.32,-0.03l0.33,0.79l0.39,-0.21l0.49,0.35l-0.01,0.57l0.37,0.23l-0.17,0.61l0.52,-0.21l0.14,-0.48l-0.47,-0.47l0.67,-0.98l-1.24,-0.29l-0.5,-0.76h-0.39l0.23,-0.81l0.89,-0.05l2.83,-1.6l-1.93,0.28l-1.28,-0.4l0.08,-0.21l-1.25,0.46l0.03,-1.39l1.41,-1.36l-0.19,-1.3l0.4,-0.91l0.53,-0.21l0.77,0.72l-0.44,0.51l0.13,0.35l-0.84,0.56l1.83,-0.13l0.42,0.41l0.55,-0.47l1.1,-0.03l0.04,-0.67l0.56,-0.62l4.8,-0.3l0.5,-0.31l0.48,0.36l1.79,-0.42l0.59,-0.41l0.02,-0.93l0.38,-0.37l-0.31,-0.24l0.37,-0.53l0.33,0.46l0.35,-0.5l0.15,-1.38l0.6,-0.59L111.63,754.38zM88.97,753.12l0.99,0.32l0.55,0.82l-0.11,-0.44l0.62,0.02l0.15,-0.28l1.31,0.48l-0.51,1.44l0.39,0.35l-1.15,0.46l0.22,-0.42l-0.88,-0.53l-0.07,0.66l-1.09,1.25l-1.35,0.03l0.57,0.7l-0.23,0.38l-1.65,-0.29l-1.7,0.46l-0.85,-0.28l0.4,-1.04l0.19,0.51l1.28,-0.2l0.17,0.22l0.27,-0.27l0.96,0.33l-0.11,-0.55l0.35,-0.53l-0.44,-0.1l-0.23,0.5l-1.21,0.25l0.16,-0.3l-0.99,-0.18l-0.29,-0.58l-0.47,0.5l-0.56,-0.73l0.03,-0.93l0.4,-0.04L84,754.56l0.49,-0.41l-0.44,-0.59l2.86,-0.54l0.89,0.17l0.28,0.37l0.38,-0.5L88.97,753.12zM81.25,752.88l0.83,0.79l-0.42,0.9l-0.61,0.1l-2.79,-0.91l1.06,-0.21l-0.05,-0.3l0.97,-0.43L81.25,752.88zM69.96,751.02l1.06,0.32l0.03,0.59l0.66,0.1l0.09,0.54l-2.02,-0.32l0.18,-0.48l-0.65,-0.61L69.96,751.02zM94.35,750.62l-0.46,0.74l0.33,0.13l-0.07,0.44l0.88,-0.05l0.54,0.51l1.29,0.01l0.5,-0.35l0.19,0.34l-2.36,2.38l-2.56,0.55l0.11,-1.43l-2.1,-0.5v-0.33l0.44,-1.17l0.77,-0.03l-0.33,-0.71l0.54,0.12l2.39,-0.89L94.35,750.62zM90.26,750.22l0.35,1.15l-1,0.44l-3.04,0.78l-0.56,-0.38l0.24,-0.58l-0.7,0.26l-0.11,-0.25l1.47,-0.74L90.26,750.22zM96.07,748.21l0.11,0.4l-0.95,1.34l-2,0.39L92,751l-1.33,-0.15l0.07,-0.81l0.38,-0.32L96.07,748.21zM88.05,746.75l0.13,0.5l0.72,0.45l0.44,1.2l0.34,-0.04l0.05,0.51l-1.04,-0.65l0.1,0.62l-0.75,0.38l-0.77,-0.23l-0.92,0.23l-0.75,-1.22l0.11,-0.52l1.37,-0.72l0.24,-0.49L88.05,746.75zM74.54,745.67l0.88,0.87l-0.29,0.87l-1.22,-0.21l-0.04,-0.36l0.99,-0.13l-0.9,-0.64l0.17,-0.45L74.54,745.67zM69.21,745.14l0.24,1.93l-0.65,-0.28l0.18,0.89l-0.83,0.74l0.07,-2.09l0.86,-1.41L69.21,745.14zM78.5,743.26l1.71,0.61l0.28,0.57l0.24,-0.17l0.96,0.6l0.29,0.49l-0.23,0.63l0.82,0.09l0.4,-0.32l0.02,1.29l-1.04,0.33l-0.2,-0.39l-0.31,0.39l-0.82,-0.08l-0.27,-1.02l-1.28,-0.49l-0.19,-0.76l-0.66,-0.31l0.37,-0.17L78.5,743.26zM76.13,742.98l1.54,0.84l1.24,2.75l0.51,0.2l0.09,0.65l0.58,0.35l0.11,0.94l-0.63,1.07l1.85,0.16l-0.21,0.51l0.79,0.3l-0.25,0.59l0.63,-0.01l0.08,0.47l-0.78,0.28l0.1,0.34l-3.66,-0.19l-0.4,-0.42l-0.61,0.12l-1.74,-0.5l-0.16,-0.56l1.65,0.06l-2.48,-1.5l-0.21,-0.54l1.07,-0.75l-0.99,0.06l0.12,-0.42l0.97,-0.08l0.46,-1.16l-0.78,-0.5l-0.2,-0.66l0.23,-2.14l0.62,-0.06l0.01,-0.33L76.13,742.98zM73.13,738.67l0.66,0.65l-0.01,-0.5l0.44,0.25l0.34,0.58l-0.12,0.71l-0.71,0.7l0.04,0.46l-0.31,0.04l0.2,0.3l-0.73,0.19l-0.62,0.77l0.28,1.32l-0.43,-0.06l-0.45,1.09l-0.63,-0.89l0.49,-0.73l-0.08,-0.56l-0.39,-0.21l0.51,-0.84l-0.34,-0.56l0.48,-0.82l0.66,-0.14L73.13,738.67zM66.25,738.92l0.47,1.37l-0.43,0.18l-0.67,-1.21l0.05,-0.56L66.25,738.92zM56.27,736.66l0.82,0.38l0.26,0.66l0.89,0.42l0.3,0.83l0.28,-0.05l0.16,2.06l0.57,0.3l0.2,0.9l0.41,0.04L60,742.63l-0.96,0.01l-0.07,0.39l-1,-0.18l-0.41,-0.39l0.43,-0.38h-0.71l-0.13,-0.38l0.43,-0.06l-0.03,-0.34l-0.89,0.47l-0.26,-0.21l0.01,-0.99l1.23,0.03l0.26,-0.27l-0.43,-1.18l-0.97,-0.34l0.16,-0.23l-0.56,-1.04L56.27,736.66zM60.94,736l0.58,0.16l0.19,0.75l0.53,0.31l-0.02,1.48l1.15,0.3l-0.21,-0.59l0.73,0.14l0.17,0.82l0.28,-0.06l0.01,-0.49l0.61,0.27l0.66,0.77l-0.19,0.43l0.5,0.14l-0.14,0.38l-0.51,-0.06l-0.11,-0.55l-1.08,-0.28l0.09,1.43l0.65,1.21l-0.95,1.14l-1.13,-0.44l-0.05,-1.1l-0.96,-0.32l-0.55,-0.7l-0.07,-0.9l-0.52,0.25l-1.21,-1.08l0.51,-2.21l0.08,0.29l0.57,-0.51l0.31,-0.49l-0.16,-0.47L60.94,736zM55.28,734.78l0.21,0.59l0.45,0.04l0.35,0.5l-0.43,0.35l0.27,0.26l-0.15,0.47l-0.69,-1.29l-0.8,-0.68l-0.52,0.19v-0.34l0.5,-0.15l0.48,0.42l-0.08,-0.4L55.28,734.78zM55.85,733.88l0.67,0.61l-0.29,0.85l-0.57,-0.86l0.37,-0.17L55.85,733.88zM57.59,731.27l0.62,-0.07l-0.07,0.58l0.49,-0.35l0.49,0.12l0.01,0.87l-0.36,-0.2l-0.27,0.89l0.25,-0.21l0.63,0.66l0.23,-0.23l0.56,0.89l-0.5,0.17l-0.14,0.44l0.58,-0.03l-0.06,0.73l0.5,0.36l0.15,0.7l-0.24,0.31l-1.77,-2.41l0.01,0.98l0.5,1.13l-0.39,0.7l-0.89,-0.46l0.23,-0.25l-0.5,-1.27l-0.6,0.46l-0.56,-0.68l0.24,-0.46l-0.57,-0.81l-0.12,-0.96l0.32,0.07l-0.15,-0.42l0.63,-0.29l0.22,0.4l0.6,-0.33l0.36,-0.57l-0.97,-0.35L57.59,731.27zM59.79,724.84l1.03,1.05l-0.52,0.64l-1.09,-1.28l0.12,-0.39L59.79,724.84zM53.56,722.36l1.02,1.13l0,0.47l-1.17,-0.33l-0.33,-0.98l0.31,-0.68L53.56,722.36zM57.7,721.74l0.4,0.28l-0.52,0.54l-0.4,-0.33l-0.56,0.16l0.91,-1.02L57.7,721.74zM57.25,718.96l0.54,2.02l-0.62,0.48l0.13,-0.6l-0.58,-0.07l0.32,0.6l-0.61,0.57l-0.18,-0.44l0.32,-0.24l-0.45,-1.01l0.55,0.07l-0.57,-0.28l0.05,-0.37l0.27,-0.22l0.46,0.48L57.25,718.96zM55.5,716.6l0.5,0.63l0.33,-0.45l1.5,0.1l-0.45,0.44l0.15,0.52l-1.01,0.53l-0.5,1.57l-0.61,0.1l-0.77,-1.37l1.04,-0.34l0.19,-0.54l-0.59,0.09l-0.14,0.37l-0.49,-0.19l-0.04,0.31l-0.14,-0.96l0.18,-0.46L55.5,716.6zM62.27,706.43l0.33,1.35l1.96,1.69l0,0l2.38,-0.43l0,0l1.29,-0.01l0.08,-1.64l0,0l0.38,-1.08l1.43,3.6l1.06,-0.59l0.57,0.41l0.62,-0.24l0.95,-0.78l-0.41,-0.86l0.72,-0.51l1.52,-0.01l-0.63,0.93l1.24,0.72l1.3,1.64l0.68,-0.22l0.63,0.57l0.86,0.03l-0.1,2.17l1.58,2.21l-0.34,0.71l0.49,0.26l0.37,-0.27l3.68,-0.2l0.97,1.95l0.39,-0.18l0.62,-1.29l0.81,0.34l0.08,-0.26l-0.93,-0.43l1.4,-1.27l0.98,-0.39l1.68,0.75l1.49,-1.11l5.06,-1.17l2.07,0.74l-1.89,-2.42l1.77,-0.93l3.8,0.25l0.44,0.32l2.61,-1.24l0.61,0.39l0.43,-1.41l-0.6,-1.69l0.61,-0.23l-0.1,-0.48l0.43,-0.74l-0.67,-1.03l0.25,-1.45l1.41,1.13l0.46,1.67l1.03,0.47l0.4,-0.18l0.29,0.74l1.1,0.03l1.45,1.35l1.27,-0.6l3,0.07l0.56,1.67l1.04,0.25l0,0l1.73,2.46l1.31,0.63l-0.15,0.8l0.31,0.35l-0.36,1.3l-1.16,-0.18l0.44,2l-3.45,-0.22l-0.62,0.5l0.09,2.97l2.79,0.91l-0.93,0.56l-1.41,2.76l0.5,0.63l2.38,2.08l0.96,1.31l0.18,-0.83l1.69,0.51l3.44,-1.93l1.45,0.02l0.49,0.2l-0.01,1.1l0.88,0.61l0.42,0.96l1.02,0.55l1.57,0.05l1.84,0.71l-0.2,0.81l0.31,0.86l1.01,-0.38l1,0.74l2.13,-0.25l2.76,0.4l0,0l-1.03,2l1.59,0.77l0.02,0.38l-0.98,1.83l0,0.94l-1.35,0.14l0.6,1.12l-0.44,0.56l0.5,0.66l0.02,1.02l-0.86,0.88l-0.7,-0.2l-2.58,0.28l-1.32,2.6l2.84,0.02l0.29,1.33l-0.16,2.77l-0.48,0.01l-0.91,1l-0.67,0.13l0.36,2.01l-0.23,1.97l-1.23,0.88l-0.51,-0.57l-0.93,1.24l-0.51,0.1l-0.05,1.39l-0.35,-0.71l-0.12,0.64l-0.56,-0.12l-0.3,0.37l1.93,1.34l-0.38,0.22l0.51,2.02l-1.16,0.67l-0.83,-0.54l-1.07,-0.13l-2.76,1.95l-1.58,0.42l-1.16,-0.12l-0.53,1.06l-1.51,-1.41l0.31,-0.98l-0.62,-0.04l-0.75,0.77l-0.14,1.44l-2.06,1.26l-0.63,0.05l0.01,0.7l-1.51,1.38l-2.57,0.35l-0.41,0.52l-0.94,-0.87l0,0l0.28,-0.29l-0.18,-1.06l-0.39,-0.18l-0.86,1.01l-0.57,-0.01l0.45,-0.51l-0.6,-0.45l0.63,-0.29l-2.65,-0.91l0.08,-0.4l-0.91,-0.47l-0.11,-1.16l0.53,-0.26l-0.59,-1.45l1.36,-2.24l1.11,-0.86l-0.06,-1.12l0.82,-0.35l0.18,-0.97l1.01,-0.09l1.24,-2.88l0.18,-1.18l1.27,-1.21l-0.63,-0.5l-0.8,0.62l0.32,0.52l-1.05,1l0.04,0.73l-0.72,0.44l-0.53,-0.49l-1.43,0.99l-2.06,0.64l-0.8,1.51l-2.02,1.8l-2.22,0.79l-1.37,-0.11l-1.99,0.53l-1.5,1.43l-1.66,0.17l0.3,-1.04l0.94,-0.15l-0.18,-0.3l1.29,-0.6l-0.92,-0.89l-0.07,-0.68l-1.09,0.12l0.22,0.46l-0.23,0.26l-0.66,-0.22l-0.04,0.46l-0.43,0.01l-0.18,-0.38l-0.51,0.18l-0.6,-0.65l0.68,-0.02l-0.08,-1.08l2.99,-3.53l-0.31,-0.58l0.22,-0.49l0.41,0.2l0.78,-0.67l0.12,-0.9l1.35,-1.99l-0.5,0.11l-1.49,1.83l-0.94,-0.52l-0.44,0.27l-1.43,-0.1l-0.76,-0.41l0.96,-1.95l-3.64,1.51l-3.01,0.78l-0.29,-0.2v-1.38l-0.44,0.08l-0.74,-1l-0.34,0.01l-0.97,-1.49l-2.63,0.32l-0.28,-0.28l0.22,-0.73l-1.02,0.74l-0.97,-0.8l-1.24,-0.23l-0.32,-1.29l0.52,-0.03l-0.17,-0.66l-1.12,0.07l-0.19,-0.53l0.48,-1.04l-0.69,0.64l-0.76,-0.36l0.46,-0.56l-0.29,-0.8l0.34,-0.42l-0.68,0.27l-0.83,-0.36l0.27,-0.73l-0.98,-0.27l-0.34,1.52l-0.28,-0.14l0.19,-0.93l-0.58,-0.21l-0.09,0.38l0.55,1.28l0,1.24l0.4,0.16l-0.13,0.49l0.41,0.38l-0.41,0.61l-0.77,-0.82l-1.34,-0.49l-0.28,0.73l-0.11,-0.21L74.33,743l-0.18,-0.3l-0.7,0.25l0.13,0.97l-0.44,0.03l0.2,-0.25l-0.7,-0.17l-0.14,-0.81l0.72,-0.26l0.07,-0.42l1.24,-0.04l-0.13,-0.89l0.51,-0.55l-0.06,-0.86l0.42,-0.42l-0.41,-1l0.51,-0.08l-0.46,-0.52l0.07,-0.6l0.35,-0.1l-0.23,-0.87l0.67,-0.18l-0.42,-0.57l0.14,-0.48l0.42,0.06l-0.12,-1.04l0.4,-1.16l-2.12,1.89l-0.81,1.37l-1,0.36l-0.39,-0.25l-1.17,0.9l-0.37,-0.23l0.37,2.08l-0.2,0.59l-0.44,0.19l-0.23,1.43l-0.9,1.12l-1.35,0.66l-0.39,-0.73l0.54,-0.97l0.5,-0.1l-0.27,-1.01l-0.9,-0.82l-0.33,-1.09l-2.56,-1.18l-0.61,0.06l0.04,-0.33l-1.18,-1.13l0.41,-0.06l0.05,-0.59l-0.34,-0.12l-0.11,-0.91l0.17,-0.51l0.23,0.63l0.47,-0.29l-0.37,-0.51l0.38,-0.16l-0.13,-0.5l-1.22,0.01l-2.44,-2.42l0.69,-0.57l0.06,-0.52L59.74,729l0.31,-0.88l1.77,0.1l0.49,0.68l1.42,0.12l-0.4,-0.83l0.37,0.01l-0.13,-0.31l-1.07,-1.3l1.19,-0.37l-0.79,-0.18l-0.17,-0.53l-1.34,-0.76l-0.2,-0.45l0.72,-0.84l-1.04,-0.86l0.61,-0.55l-0.11,-0.83l-0.43,-0.2l-0.31,0.37l-0.18,-0.38l-0.3,0.32l0.21,-1.8l-0.23,0.39l-0.49,-0.25l0.58,-0.9l-1.73,-0.62l1.11,-0.32l0.16,-0.85h1.54l0.85,0.64l0.04,-0.41l0.65,-0.15l0.13,-0.34l-0.23,-0.32l-1.27,-0.06l-0.52,-1.39l-1.01,-0.86l1.34,2.34l-0.44,-0.22l-1.13,0.47l-2.3,-0.83l0.06,0.37l0.74,0.01l0.14,0.28l-1.33,0.2l-0.91,-0.21l-0.22,-0.31l0.32,-0.18l-0.66,-0.31l0.66,-0.28l-0.39,-0.39l0.61,0.07l0.54,-0.65l1.11,0.6l-0.07,-0.59l1.18,-0.05l-0.73,-1.22l0.57,-0.13l0.18,-0.72l-2.55,-1.61l0.46,-0.11l0.02,-0.53l0.61,0.03l0.13,-0.57l0.56,-0.3l1.6,2.14l0.11,0.79l0.33,-0.03l0.49,0.78l0.34,-0.3l0.52,0.95l-0.24,0.55l-0.73,-0.24l-0.29,0.42l1.09,0.15l0.35,-0.34l0.96,1.34l0.23,-0.7l-0.58,-1.04l0.3,-0.85l-0.31,-0.64l-0.75,-0.24l0.12,-0.65l-1.29,-1.36l-0.3,-1.27l-0.65,-0.21l0.48,-0.68l-1.12,-0.75l0.8,-1.04l-0.79,0.11l-0.46,-0.4l-0.27,-1.93l0.86,0.14l0.34,0.56l1.91,1.01L62.27,706.43z"}]}}}; | zimbatm/cdnjs | ajax/libs/ammaps/3.10.0/maps/js/finlandLow.min.js | JavaScript | mit | 105,484 |
/*
This file is part of Ext JS 3.4
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-04-03 15:07:25
*/
/**
* W3C Suggested Default style sheet for HTML 4
* http://www.w3.org/TR/CSS21/sample.html
*
* Resets for Ext.Panel @cfg normal: true
*/
.x-panel-reset .x-panel-body html,
.x-panel-reset .x-panel-body address,
.x-panel-reset .x-panel-body blockquote,
.x-panel-reset .x-panel-body body,
.x-panel-reset .x-panel-body dd,
.x-panel-reset .x-panel-body div,
.x-panel-reset .x-panel-body dl,
.x-panel-reset .x-panel-body dt,
.x-panel-reset .x-panel-body fieldset,
.x-panel-reset .x-panel-body form,
.x-panel-reset .x-panel-body frame, frameset,
.x-panel-reset .x-panel-body h1,
.x-panel-reset .x-panel-body h2,
.x-panel-reset .x-panel-body h3,
.x-panel-reset .x-panel-body h4,
.x-panel-reset .x-panel-body h5,
.x-panel-reset .x-panel-body h6,
.x-panel-reset .x-panel-body noframes,
.x-panel-reset .x-panel-body ol,
.x-panel-reset .x-panel-body p,
.x-panel-reset .x-panel-body ul,
.x-panel-reset .x-panel-body center,
.x-panel-reset .x-panel-body dir,
.x-panel-reset .x-panel-body hr,
.x-panel-reset .x-panel-body menu,
.x-panel-reset .x-panel-body pre { display: block }
.x-panel-reset .x-panel-body li { display: list-item }
.x-panel-reset .x-panel-body head { display: none }
.x-panel-reset .x-panel-body table { display: table }
.x-panel-reset .x-panel-body tr { display: table-row }
.x-panel-reset .x-panel-body thead { display: table-header-group }
.x-panel-reset .x-panel-body tbody { display: table-row-group }
.x-panel-reset .x-panel-body tfoot { display: table-footer-group }
.x-panel-reset .x-panel-body col { display: table-column }
.x-panel-reset .x-panel-body colgroup { display: table-column-group }
.x-panel-reset .x-panel-body td,
.x-panel-reset .x-panel-body th { display: table-cell }
.x-panel-reset .x-panel-body caption { display: table-caption }
.x-panel-reset .x-panel-body th { font-weight: bolder; text-align: center }
.x-panel-reset .x-panel-body caption { text-align: center }
.x-panel-reset .x-panel-body body { margin: 8px }
.x-panel-reset .x-panel-body h1 { font-size: 2em; margin: .67em 0 }
.x-panel-reset .x-panel-body h2 { font-size: 1.5em; margin: .75em 0 }
.x-panel-reset .x-panel-body h3 { font-size: 1.17em; margin: .83em 0 }
.x-panel-reset .x-panel-body h4,
.x-panel-reset .x-panel-body p,
.x-panel-reset .x-panel-body blockquote,
.x-panel-reset .x-panel-body ul,
.x-panel-reset .x-panel-body fieldset,
.x-panel-reset .x-panel-body form,
.x-panel-reset .x-panel-body ol,
.x-panel-reset .x-panel-body dl,
.x-panel-reset .x-panel-body dir,
.x-panel-reset .x-panel-body menu { margin: 1.12em 0 }
.x-panel-reset .x-panel-body h5 { font-size: .83em; margin: 1.5em 0 }
.x-panel-reset .x-panel-body h6 { font-size: .75em; margin: 1.67em 0 }
.x-panel-reset .x-panel-body h1,
.x-panel-reset .x-panel-body h2,
.x-panel-reset .x-panel-body h3,
.x-panel-reset .x-panel-body h4,
.x-panel-reset .x-panel-body h5,
.x-panel-reset .x-panel-body h6,
.x-panel-reset .x-panel-body b,
.x-panel-reset .x-panel-body strong { font-weight: bolder }
.x-panel-reset .x-panel-body blockquote { margin-left: 40px; margin-right: 40px }
.x-panel-reset .x-panel-body i,
.x-panel-reset .x-panel-body cite,
.x-panel-reset .x-panel-body em,
.x-panel-reset .x-panel-body var,
.x-panel-reset .x-panel-body address { font-style: italic }
.x-panel-reset .x-panel-body pre,
.x-panel-reset .x-panel-body tt,
.x-panel-reset .x-panel-body code,
.x-panel-reset .x-panel-body kbd,
.x-panel-reset .x-panel-body samp { font-family: monospace }
.x-panel-reset .x-panel-body pre { white-space: pre }
.x-panel-reset .x-panel-body button,
.x-panel-reset .x-panel-body textarea,
.x-panel-reset .x-panel-body input,
.x-panel-reset .x-panel-body select { display: inline-block }
.x-panel-reset .x-panel-body big { font-size: 1.17em }
.x-panel-reset .x-panel-body small,
.x-panel-reset .x-panel-body sub,
.x-panel-reset .x-panel-body sup { font-size: .83em }
.x-panel-reset .x-panel-body sub { vertical-align: sub }
.x-panel-reset .x-panel-body sup { vertical-align: super }
.x-panel-reset .x-panel-body table { border-spacing: 2px; }
.x-panel-reset .x-panel-body thead,
.x-panel-reset .x-panel-body tbody,
.x-panel-reset .x-panel-body tfoot { vertical-align: middle }
.x-panel-reset .x-panel-body td,
.x-panel-reset .x-panel-body th { vertical-align: inherit }
.x-panel-reset .x-panel-body s,
.x-panel-reset .x-panel-body strike,
.x-panel-reset .x-panel-body del { text-decoration: line-through }
.x-panel-reset .x-panel-body hr { border: 1px inset }
.x-panel-reset .x-panel-body ol,
.x-panel-reset .x-panel-body ul,
.x-panel-reset .x-panel-body dir,
.x-panel-reset .x-panel-body menu,
.x-panel-reset .x-panel-body dd { margin-left: 40px }
.x-panel-reset .x-panel-body ul, .x-panel-reset .x-panel-body menu, .x-panel-reset .x-panel-body dir { list-style-type: disc;}
.x-panel-reset .x-panel-body ol { list-style-type: decimal }
.x-panel-reset .x-panel-body ol ul,
.x-panel-reset .x-panel-body ul ol,
.x-panel-reset .x-panel-body ul ul,
.x-panel-reset .x-panel-body ol ol { margin-top: 0; margin-bottom: 0 }
.x-panel-reset .x-panel-body u,
.x-panel-reset .x-panel-body ins { text-decoration: underline }
.x-panel-reset .x-panel-body br:before { content: "\A" }
.x-panel-reset .x-panel-body :before, .x-panel-reset .x-panel-body :after { white-space: pre-line }
.x-panel-reset .x-panel-body center { text-align: center }
.x-panel-reset .x-panel-body :link, .x-panel-reset .x-panel-body :visited { text-decoration: underline }
.x-panel-reset .x-panel-body :focus { outline: invert dotted thin }
/* Begin bidirectionality settings (do not change) */
.x-panel-reset .x-panel-body BDO[DIR="ltr"] { direction: ltr; unicode-bidi: bidi-override }
.x-panel-reset .x-panel-body BDO[DIR="rtl"] { direction: rtl; unicode-bidi: bidi-override }
| Nadeermalangadan/cdnjs | ajax/libs/extjs/3.4.1-1/resources/css/structure/panel-reset.css | CSS | mit | 6,824 |
//! moment.js locale configuration
//! locale : Lithuanian (lt)
//! author : Mindaugas Mozūras : https://github.com/mmozuras
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var units = {
'm' : 'minutė_minutės_minutę',
'mm': 'minutės_minučių_minutes',
'h' : 'valanda_valandos_valandą',
'hh': 'valandos_valandų_valandas',
'd' : 'diena_dienos_dieną',
'dd': 'dienos_dienų_dienas',
'M' : 'mėnuo_mėnesio_mėnesį',
'MM': 'mėnesiai_mėnesių_mėnesius',
'y' : 'metai_metų_metus',
'yy': 'metai_metų_metus'
};
function translateSeconds(number, withoutSuffix, key, isFuture) {
if (withoutSuffix) {
return 'kelios sekundės';
} else {
return isFuture ? 'kelių sekundžių' : 'kelias sekundes';
}
}
function translateSingular(number, withoutSuffix, key, isFuture) {
return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]);
}
function special(number) {
return number % 10 === 0 || (number > 10 && number < 20);
}
function forms(key) {
return units[key].split('_');
}
function translate(number, withoutSuffix, key, isFuture) {
var result = number + ' ';
if (number === 1) {
return result + translateSingular(number, withoutSuffix, key[0], isFuture);
} else if (withoutSuffix) {
return result + (special(number) ? forms(key)[1] : forms(key)[0]);
} else {
if (isFuture) {
return result + forms(key)[1];
} else {
return result + (special(number) ? forms(key)[1] : forms(key)[2]);
}
}
}
var lt = moment.defineLocale('lt', {
months : {
format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'),
standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_')
},
monthsShort : 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'),
weekdays : {
format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'),
standalone: 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'),
isFormat: /dddd HH:mm/
},
weekdaysShort : 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'),
weekdaysMin : 'S_P_A_T_K_Pn_Š'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'YYYY-MM-DD',
LL : 'YYYY [m.] MMMM D [d.]',
LLL : 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
LLLL : 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]',
l : 'YYYY-MM-DD',
ll : 'YYYY [m.] MMMM D [d.]',
lll : 'YYYY [m.] MMMM D [d.], HH:mm [val.]',
llll : 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]'
},
calendar : {
sameDay : '[Šiandien] LT',
nextDay : '[Rytoj] LT',
nextWeek : 'dddd LT',
lastDay : '[Vakar] LT',
lastWeek : '[Praėjusį] dddd LT',
sameElse : 'L'
},
relativeTime : {
future : 'po %s',
past : 'prieš %s',
s : translateSeconds,
m : translateSingular,
mm : translate,
h : translateSingular,
hh : translate,
d : translateSingular,
dd : translate,
M : translateSingular,
MM : translate,
y : translateSingular,
yy : translate
},
ordinalParse: /\d{1,2}-oji/,
ordinal : function (number) {
return number + '-oji';
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return lt;
})); | cyberpuffin/remanddel | node_modules/concurrently/node_modules/moment/locale/lt.js | JavaScript | mit | 4,427 |
/**
* impress.js
*
* impress.js is a presentation tool based on the power of CSS3 transforms and transitions
* in modern browsers and inspired by the idea behind prezi.com.
*
*
* Copyright 2011-2012 Bartek Szopka (@bartaz)
*
* Released under the MIT and GPL Licenses.
*
* ------------------------------------------------
* author: Bartek Szopka
* version: 0.5.3
* url: http://bartaz.github.com/impress.js/
* source: http://github.com/bartaz/impress.js/
*/
/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, latedef:true, newcap:true,
noarg:true, noempty:true, undef:true, strict:true, browser:true */
// You are one of those who like to know how thing work inside?
// Let me show you the cogs that make impress.js run...
(function ( document, window ) {
'use strict';
// HELPER FUNCTIONS
// `pfx` is a function that takes a standard CSS property name as a parameter
// and returns it's prefixed version valid for current browser it runs in.
// The code is heavily inspired by Modernizr http://www.modernizr.com/
var pfx = (function () {
var style = document.createElement('dummy').style,
prefixes = 'Webkit Moz O ms Khtml'.split(' '),
memory = {};
return function ( prop ) {
if ( typeof memory[ prop ] === "undefined" ) {
var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1),
props = (prop + ' ' + prefixes.join(ucProp + ' ') + ucProp).split(' ');
memory[ prop ] = null;
for ( var i in props ) {
if ( style[ props[i] ] !== undefined ) {
memory[ prop ] = props[i];
break;
}
}
}
return memory[ prop ];
};
})();
// `arraify` takes an array-like object and turns it into real Array
// to make all the Array.prototype goodness available.
var arrayify = function ( a ) {
return [].slice.call( a );
};
// `css` function applies the styles given in `props` object to the element
// given as `el`. It runs all property names through `pfx` function to make
// sure proper prefixed version of the property is used.
var css = function ( el, props ) {
var key, pkey;
for ( key in props ) {
if ( props.hasOwnProperty(key) ) {
pkey = pfx(key);
if ( pkey !== null ) {
el.style[pkey] = props[key];
}
}
}
return el;
};
// `toNumber` takes a value given as `numeric` parameter and tries to turn
// it into a number. If it is not possible it returns 0 (or other value
// given as `fallback`).
var toNumber = function (numeric, fallback) {
return isNaN(numeric) ? (fallback || 0) : Number(numeric);
};
// `byId` returns element with given `id` - you probably have guessed that ;)
var byId = function ( id ) {
return document.getElementById(id);
};
// `$` returns first element for given CSS `selector` in the `context` of
// the given element or whole document.
var $ = function ( selector, context ) {
context = context || document;
return context.querySelector(selector);
};
// `$$` return an array of elements for given CSS `selector` in the `context` of
// the given element or whole document.
var $$ = function ( selector, context ) {
context = context || document;
return arrayify( context.querySelectorAll(selector) );
};
// `triggerEvent` builds a custom DOM event with given `eventName` and `detail` data
// and triggers it on element given as `el`.
var triggerEvent = function (el, eventName, detail) {
var event = document.createEvent("CustomEvent");
event.initCustomEvent(eventName, true, true, detail);
el.dispatchEvent(event);
};
// `translate` builds a translate transform string for given data.
var translate = function ( t ) {
return " translate3d(" + t.x + "px," + t.y + "px," + t.z + "px) ";
};
// `rotate` builds a rotate transform string for given data.
// By default the rotations are in X Y Z order that can be reverted by passing `true`
// as second parameter.
var rotate = function ( r, revert ) {
var rX = " rotateX(" + r.x + "deg) ",
rY = " rotateY(" + r.y + "deg) ",
rZ = " rotateZ(" + r.z + "deg) ";
return revert ? rZ+rY+rX : rX+rY+rZ;
};
// `scale` builds a scale transform string for given data.
var scale = function ( s ) {
return " scale(" + s + ") ";
};
// `perspective` builds a perspective transform string for given data.
var perspective = function ( p ) {
return " perspective(" + p + "px) ";
};
// `getElementFromHash` returns an element located by id from hash part of
// window location.
var getElementFromHash = function () {
// get id from url # by removing `#` or `#/` from the beginning,
// so both "fallback" `#slide-id` and "enhanced" `#/slide-id` will work
return byId( window.location.hash.replace(/^#\/?/,"") );
};
// `computeWindowScale` counts the scale factor between window size and size
// defined for the presentation in the config.
var computeWindowScale = function ( config ) {
var hScale = window.innerHeight / config.height,
wScale = window.innerWidth / config.width,
scale = hScale > wScale ? wScale : hScale;
if (config.maxScale && scale > config.maxScale) {
scale = config.maxScale;
}
if (config.minScale && scale < config.minScale) {
scale = config.minScale;
}
return scale;
};
// CHECK SUPPORT
var body = document.body;
var ua = navigator.userAgent.toLowerCase();
var impressSupported =
// browser should support CSS 3D transtorms
( pfx("perspective") !== null ) &&
// and `classList` and `dataset` APIs
( body.classList ) &&
( body.dataset ) &&
// but some mobile devices need to be blacklisted,
// because their CSS 3D support or hardware is not
// good enough to run impress.js properly, sorry...
( ua.search(/(iphone)|(ipod)|(android)/) === -1 );
if (!impressSupported) {
// we can't be sure that `classList` is supported
body.className += " impress-not-supported ";
} else {
body.classList.remove("impress-not-supported");
body.classList.add("impress-supported");
}
// GLOBALS AND DEFAULTS
// This is were the root elements of all impress.js instances will be kept.
// Yes, this means you can have more than one instance on a page, but I'm not
// sure if it makes any sense in practice ;)
var roots = {};
// some default config values.
var defaults = {
width: 1024,
height: 768,
maxScale: 1,
minScale: 0,
perspective: 1000,
transitionDuration: 1000
};
// it's just an empty function ... and a useless comment.
var empty = function () { return false; };
// IMPRESS.JS API
// And that's where interesting things will start to happen.
// It's the core `impress` function that returns the impress.js API
// for a presentation based on the element with given id ('impress'
// by default).
var impress = window.impress = function ( rootId ) {
// If impress.js is not supported by the browser return a dummy API
// it may not be a perfect solution but we return early and avoid
// running code that may use features not implemented in the browser.
if (!impressSupported) {
return {
init: empty,
goto: empty,
prev: empty,
next: empty
};
}
rootId = rootId || "impress";
// if given root is already initialized just return the API
if (roots["impress-root-" + rootId]) {
return roots["impress-root-" + rootId];
}
// data of all presentation steps
var stepsData = {};
// element of currently active step
var activeStep = null;
// current state (position, rotation and scale) of the presentation
var currentState = null;
// array of step elements
var steps = null;
// configuration options
var config = null;
// scale factor of the browser window
var windowScale = null;
// root presentation elements
var root = byId( rootId );
var canvas = document.createElement("div");
var initialized = false;
// STEP EVENTS
//
// There are currently two step events triggered by impress.js
// `impress:stepenter` is triggered when the step is shown on the
// screen (the transition from the previous one is finished) and
// `impress:stepleave` is triggered when the step is left (the
// transition to next step just starts).
// reference to last entered step
var lastEntered = null;
// `onStepEnter` is called whenever the step element is entered
// but the event is triggered only if the step is different than
// last entered step.
var onStepEnter = function (step) {
if (lastEntered !== step) {
triggerEvent(step, "impress:stepenter");
lastEntered = step;
}
};
// `onStepLeave` is called whenever the step element is left
// but the event is triggered only if the step is the same as
// last entered step.
var onStepLeave = function (step) {
if (lastEntered === step) {
triggerEvent(step, "impress:stepleave");
lastEntered = null;
}
};
// `initStep` initializes given step element by reading data from its
// data attributes and setting correct styles.
var initStep = function ( el, idx ) {
var data = el.dataset,
step = {
translate: {
x: toNumber(data.x),
y: toNumber(data.y),
z: toNumber(data.z)
},
rotate: {
x: toNumber(data.rotateX),
y: toNumber(data.rotateY),
z: toNumber(data.rotateZ || data.rotate)
},
scale: toNumber(data.scale, 1),
el: el
};
if ( !el.id ) {
el.id = "step-" + (idx + 1);
}
stepsData["impress-" + el.id] = step;
css(el, {
position: "absolute",
transform: "translate(-50%,-50%)" +
translate(step.translate) +
rotate(step.rotate) +
scale(step.scale),
transformStyle: "preserve-3d"
});
};
// `init` API function that initializes (and runs) the presentation.
var init = function () {
if (initialized) { return; }
// First we set up the viewport for mobile devices.
// For some reason iPad goes nuts when it is not done properly.
var meta = $("meta[name='viewport']") || document.createElement("meta");
meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no";
if (meta.parentNode !== document.head) {
meta.name = 'viewport';
document.head.appendChild(meta);
}
// initialize configuration object
var rootData = root.dataset;
config = {
width: toNumber( rootData.width, defaults.width ),
height: toNumber( rootData.height, defaults.height ),
maxScale: toNumber( rootData.maxScale, defaults.maxScale ),
minScale: toNumber( rootData.minScale, defaults.minScale ),
perspective: toNumber( rootData.perspective, defaults.perspective ),
transitionDuration: toNumber( rootData.transitionDuration, defaults.transitionDuration )
};
windowScale = computeWindowScale( config );
// wrap steps with "canvas" element
arrayify( root.childNodes ).forEach(function ( el ) {
canvas.appendChild( el );
});
root.appendChild(canvas);
// set initial styles
document.documentElement.style.height = "100%";
css(body, {
height: "100%",
overflow: "hidden"
});
var rootStyles = {
position: "absolute",
transformOrigin: "top left",
transition: "all 0s ease-in-out",
transformStyle: "preserve-3d"
};
css(root, rootStyles);
css(root, {
top: "50%",
left: "50%",
transform: perspective( config.perspective/windowScale ) + scale( windowScale )
});
css(canvas, rootStyles);
body.classList.remove("impress-disabled");
body.classList.add("impress-enabled");
// get and init steps
steps = $$(".step", root);
steps.forEach( initStep );
// set a default initial state of the canvas
currentState = {
translate: { x: 0, y: 0, z: 0 },
rotate: { x: 0, y: 0, z: 0 },
scale: 1
};
initialized = true;
triggerEvent(root, "impress:init", { api: roots[ "impress-root-" + rootId ] });
};
// `getStep` is a helper function that returns a step element defined by parameter.
// If a number is given, step with index given by the number is returned, if a string
// is given step element with such id is returned, if DOM element is given it is returned
// if it is a correct step element.
var getStep = function ( step ) {
if (typeof step === "number") {
step = step < 0 ? steps[ steps.length + step] : steps[ step ];
} else if (typeof step === "string") {
step = byId(step);
}
return (step && step.id && stepsData["impress-" + step.id]) ? step : null;
};
// used to reset timeout for `impress:stepenter` event
var stepEnterTimeout = null;
// `goto` API function that moves to step given with `el` parameter (by index, id or element),
// with a transition `duration` optionally given as second parameter.
var goto = function ( el, duration ) {
if ( !initialized || !(el = getStep(el)) ) {
// presentation not initialized or given element is not a step
return false;
}
// Sometimes it's possible to trigger focus on first link with some keyboard action.
// Browser in such a case tries to scroll the page to make this element visible
// (even that body overflow is set to hidden) and it breaks our careful positioning.
//
// So, as a lousy (and lazy) workaround we will make the page scroll back to the top
// whenever slide is selected
//
// If you are reading this and know any better way to handle it, I'll be glad to hear about it!
window.scrollTo(0, 0);
var step = stepsData["impress-" + el.id];
if ( activeStep ) {
activeStep.classList.remove("active");
body.classList.remove("impress-on-" + activeStep.id);
}
el.classList.add("active");
body.classList.add("impress-on-" + el.id);
// compute target state of the canvas based on given step
var target = {
rotate: {
x: -step.rotate.x,
y: -step.rotate.y,
z: -step.rotate.z
},
translate: {
x: -step.translate.x,
y: -step.translate.y,
z: -step.translate.z
},
scale: 1 / step.scale
};
// Check if the transition is zooming in or not.
//
// This information is used to alter the transition style:
// when we are zooming in - we start with move and rotate transition
// and the scaling is delayed, but when we are zooming out we start
// with scaling down and move and rotation are delayed.
var zoomin = target.scale >= currentState.scale;
duration = toNumber(duration, config.transitionDuration);
var delay = (duration / 2);
// if the same step is re-selected, force computing window scaling,
// because it is likely to be caused by window resize
if (el === activeStep) {
windowScale = computeWindowScale(config);
}
var targetScale = target.scale * windowScale;
// trigger leave of currently active element (if it's not the same step again)
if (activeStep && activeStep !== el) {
onStepLeave(activeStep);
}
// Now we alter transforms of `root` and `canvas` to trigger transitions.
//
// And here is why there are two elements: `root` and `canvas` - they are
// being animated separately:
// `root` is used for scaling and `canvas` for translate and rotations.
// Transitions on them are triggered with different delays (to make
// visually nice and 'natural' looking transitions), so we need to know
// that both of them are finished.
css(root, {
// to keep the perspective look similar for different scales
// we need to 'scale' the perspective, too
transform: perspective( config.perspective / targetScale ) + scale( targetScale ),
transitionDuration: duration + "ms",
transitionDelay: (zoomin ? delay : 0) + "ms"
});
css(canvas, {
transform: rotate(target.rotate, true) + translate(target.translate),
transitionDuration: duration + "ms",
transitionDelay: (zoomin ? 0 : delay) + "ms"
});
// Here is a tricky part...
//
// If there is no change in scale or no change in rotation and translation, it means there was actually
// no delay - because there was no transition on `root` or `canvas` elements.
// We want to trigger `impress:stepenter` event in the correct moment, so here we compare the current
// and target values to check if delay should be taken into account.
//
// I know that this `if` statement looks scary, but it's pretty simple when you know what is going on
// - it's simply comparing all the values.
if ( currentState.scale === target.scale ||
(currentState.rotate.x === target.rotate.x && currentState.rotate.y === target.rotate.y &&
currentState.rotate.z === target.rotate.z && currentState.translate.x === target.translate.x &&
currentState.translate.y === target.translate.y && currentState.translate.z === target.translate.z) ) {
delay = 0;
}
// store current state
currentState = target;
activeStep = el;
// And here is where we trigger `impress:stepenter` event.
// We simply set up a timeout to fire it taking transition duration (and possible delay) into account.
//
// I really wanted to make it in more elegant way. The `transitionend` event seemed to be the best way
// to do it, but the fact that I'm using transitions on two separate elements and that the `transitionend`
// event is only triggered when there was a transition (change in the values) caused some bugs and
// made the code really complicated, cause I had to handle all the conditions separately. And it still
// needed a `setTimeout` fallback for the situations when there is no transition at all.
// So I decided that I'd rather make the code simpler than use shiny new `transitionend`.
//
// If you want learn something interesting and see how it was done with `transitionend` go back to
// version 0.5.2 of impress.js: http://github.com/bartaz/impress.js/blob/0.5.2/js/impress.js
window.clearTimeout(stepEnterTimeout);
stepEnterTimeout = window.setTimeout(function() {
onStepEnter(activeStep);
}, duration + delay);
return el;
};
// `prev` API function goes to previous step (in document order)
var prev = function () {
var prev = steps.indexOf( activeStep ) - 1;
prev = prev >= 0 ? steps[ prev ] : steps[ steps.length-1 ];
return goto(prev);
};
// `next` API function goes to next step (in document order)
var next = function () {
var next = steps.indexOf( activeStep ) + 1;
next = next < steps.length ? steps[ next ] : steps[ 0 ];
return goto(next);
};
// Adding some useful classes to step elements.
//
// All the steps that have not been shown yet are given `future` class.
// When the step is entered the `future` class is removed and the `present`
// class is given. When the step is left `present` class is replaced with
// `past` class.
//
// So every step element is always in one of three possible states:
// `future`, `present` and `past`.
//
// There classes can be used in CSS to style different types of steps.
// For example the `present` class can be used to trigger some custom
// animations when step is shown.
root.addEventListener("impress:init", function(){
// STEP CLASSES
steps.forEach(function (step) {
step.classList.add("future");
});
root.addEventListener("impress:stepenter", function (event) {
event.target.classList.remove("past");
event.target.classList.remove("future");
event.target.classList.add("present");
}, false);
root.addEventListener("impress:stepleave", function (event) {
event.target.classList.remove("present");
event.target.classList.add("past");
}, false);
}, false);
// Adding hash change support.
root.addEventListener("impress:init", function(){
// last hash detected
var lastHash = "";
// `#/step-id` is used instead of `#step-id` to prevent default browser
// scrolling to element in hash.
//
// And it has to be set after animation finishes, because in Chrome it
// makes transtion laggy.
// BUG: http://code.google.com/p/chromium/issues/detail?id=62820
root.addEventListener("impress:stepenter", function (event) {
window.location.hash = lastHash = "#/" + event.target.id;
}, false);
window.addEventListener("hashchange", function () {
// When the step is entered hash in the location is updated
// (just few lines above from here), so the hash change is
// triggered and we would call `goto` again on the same element.
//
// To avoid this we store last entered hash and compare.
if (window.location.hash !== lastHash) {
goto( getElementFromHash() );
}
}, false);
// START
// by selecting step defined in url or first step of the presentation
goto(getElementFromHash() || steps[0], 0);
}, false);
body.classList.add("impress-disabled");
// store and return API for given impress.js root element
return (roots[ "impress-root-" + rootId ] = {
init: init,
goto: goto,
next: next,
prev: prev
});
};
// flag that can be used in JS to check if browser have passed the support test
impress.supported = impressSupported;
})(document, window);
// NAVIGATION EVENTS
// As you can see this part is separate from the impress.js core code.
// It's because these navigation actions only need what impress.js provides with
// its simple API.
//
// In future I think about moving it to make them optional, move to separate files
// and treat more like a 'plugins'.
(function ( document, window ) {
'use strict';
// throttling function calls, by Remy Sharp
// http://remysharp.com/2010/07/21/throttling-function-calls/
var throttle = function (fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
};
// wait for impress.js to be initialized
document.addEventListener("impress:init", function (event) {
// Getting API from event data.
// So you don't event need to know what is the id of the root element
// or anything. `impress:init` event data gives you everything you
// need to control the presentation that was just initialized.
var api = event.detail.api;
// KEYBOARD NAVIGATION HANDLERS
// Prevent default keydown action when one of supported key is pressed.
document.addEventListener("keydown", function ( event ) {
if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
event.preventDefault();
}
}, false);
// Trigger impress action (next or prev) on keyup.
// Supported keys are:
// [space] - quite common in presentation software to move forward
// [up] [right] / [down] [left] - again common and natural addition,
// [pgdown] / [pgup] - often triggered by remote controllers,
// [tab] - this one is quite controversial, but the reason it ended up on
// this list is quite an interesting story... Remember that strange part
// in the impress.js code where window is scrolled to 0,0 on every presentation
// step, because sometimes browser scrolls viewport because of the focused element?
// Well, the [tab] key by default navigates around focusable elements, so clicking
// it very often caused scrolling to focused element and breaking impress.js
// positioning. I didn't want to just prevent this default action, so I used [tab]
// as another way to moving to next step... And yes, I know that for the sake of
// consistency I should add [shift+tab] as opposite action...
document.addEventListener("keyup", function ( event ) {
if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
switch( event.keyCode ) {
case 33: // pg up
case 37: // left
case 38: // up
api.prev();
break;
case 9: // tab
case 32: // space
case 34: // pg down
case 39: // right
case 40: // down
api.next();
break;
}
event.preventDefault();
}
}, false);
// delegated handler for clicking on the links to presentation steps
document.addEventListener("click", function ( event ) {
// event delegation with "bubbling"
// check if event target (or any of its parents is a link)
var target = event.target;
while ( (target.tagName !== "A") &&
(target !== document.documentElement) ) {
target = target.parentNode;
}
if ( target.tagName === "A" ) {
var href = target.getAttribute("href");
// if it's a link to presentation step, target this step
if ( href && href[0] === '#' ) {
target = document.getElementById( href.slice(1) );
}
}
if ( api.goto(target) ) {
event.stopImmediatePropagation();
event.preventDefault();
}
}, false);
// delegated handler for clicking on step elements
document.addEventListener("click", function ( event ) {
var target = event.target;
// find closest step element that is not active
while ( !(target.classList.contains("step") && !target.classList.contains("active")) &&
(target !== document.documentElement) ) {
target = target.parentNode;
}
if ( api.goto(target) ) {
event.preventDefault();
}
}, false);
// touch handler to detect taps on the left and right side of the screen
// based on awesome work of @hakimel: https://github.com/hakimel/reveal.js
document.addEventListener("touchstart", function ( event ) {
if (event.touches.length === 1) {
var x = event.touches[0].clientX,
width = window.innerWidth * 0.3,
result = null;
if ( x < width ) {
result = api.prev();
} else if ( x > window.innerWidth - width ) {
result = api.next();
}
if (result) {
event.preventDefault();
}
}
}, false);
// rescale presentation when window is resized
window.addEventListener("resize", throttle(function () {
// force going to active step again, to trigger rescaling
api.goto( document.querySelector(".active"), 500 );
}, 250), false);
}, false);
})(document, window);
// THAT'S ALL FOLKS!
//
// Thanks for reading it all.
// Or thanks for scrolling down and reading the last part.
//
// I've learnt a lot when building impress.js and I hope this code and comments
// will help somebody learn at least some part of it.
| teropa/cdnjs | ajax/libs/impress.js/0.5.3/impress.js | JavaScript | mit | 32,834 |
// (c) ammap.com | SVG (in JSON format) map of Russia - High
// areas: {id:"RU-AD"},{id:"RU-ALT"},{id:"RU-AMU"},{id:"RU-ARK"},{id:"RU-AST"},{id:"RU-BA"},{id:"RU-BEL"},{id:"RU-BRY"},{id:"RU-BU"},{id:"RU-CE"},{id:"RU-CHE"},{id:"RU-CHU"},{id:"RU-CU"},{id:"RU-DA"},{id:"RU-AL"},{id:"RU-IN"},{id:"RU-IRK"},{id:"RU-IVA"},{id:"RU-KB"},{id:"RU-KC"},{id:"RU-KDA"},{id:"RU-KEM"},{id:"RU-KLU"},{id:"RU-KHA"},{id:"RU-KR"},{id:"RU-KK"},{id:"RU-KL"},{id:"RU-KHM"},{id:"RU-KGD"},{id:"RU-KO"},{id:"RU-KAM"},{id:"RU-KRS"},{id:"RU-KOS"},{id:"RU-KGN"},{id:"RU-KIR"},{id:"RU-KYA"},{id:"RU-LEN"},{id:"RU-LIP"},{id:"RU-MOW"},{id:"RU-ME"},{id:"RU-MAG"},{id:"RU-MUR"},{id:"RU-MO"},{id:"RU-MOS"},{id:"RU-NGR"},{id:"RU-NEN"},{id:"RU-SE"},{id:"RU-NVS"},{id:"RU-NIZ"},{id:"RU-ORE"},{id:"RU-ORL"},{id:"RU-OMS"},{id:"RU-PER"},{id:"RU-PRI"},{id:"RU-PSK"},{id:"RU-PNZ"},{id:"RU-ROS"},{id:"RU-RYA"},{id:"RU-SAM"},{id:"RU-SA"},{id:"RU-SAK"},{id:"RU-SMO"},{id:"RU-SPE"},{id:"RU-SAR"},{id:"RU-STA"},{id:"RU-SVE"},{id:"RU-TAM"},{id:"RU-TOM"},{id:"RU-TUL"},{id:"RU-TA"},{id:"RU-TY"},{id:"RU-TVE"},{id:"RU-TYU"},{id:"RU-UD"},{id:"RU-ULY"},{id:"RU-VGG"},{id:"RU-VLA"},{id:"RU-YAN"},{id:"RU-VLG"},{id:"RU-VOR"},{id:"RU-YAR"},{id:"RU-YEV"},{id:"RU-ZAB"}
AmCharts.maps.russiaHigh={
"svg": {
"defs": {
"amcharts:ammap": {
"projection":"mercator",
"leftLongitude":"19.642502",
"topLatitude":"81.857875",
"rightLongitude":"190.34596",
"bottomLatitude":"41.185573"
}
},
"g":{
"path":[
{
"id":"RU-AD",
"title":"Adygey",
"d":"M144.58,762.42L145.59,763.82L146.66,763.23L146.62,761.98L146.18,761.99L145.84,761.36L145.34,761.38L144.97,761L145.23,760.2L144.83,758.88L145.4,758.34L145.38,757.6L146.32,756.98L145.65,756.5L146.02,756.11L145.86,755.55L145.24,755.34L145.47,754.77L144.26,754.69L143.61,754.12L142.97,756.11L141.81,756.48L139.92,756.09L138.81,756.21L137.44,755.64L136.78,754.94L135.94,754.8L135.72,754.36L136.16,753.79L136.65,754.22L137.45,754.08L138.48,754.72L140.13,754.62L142.15,753.71L143.23,752.85L144.41,753.05L145.07,753.66L146.18,754.06L146.99,753.66L148.13,753.73L149.57,754.93L151.82,759.98L151.17,760.23L150.25,757.69L149.76,757.23L149.06,757.3L148.53,758.84L149.56,761.13L148.96,762.84L149.43,764.68L149.05,765.94L148.05,766.79L145.53,765.24L144.05,765.34L143.45,764.82L144.12,764.51L143.95,763.97L144.49,763.73L143.91,762.72L143.91,762.72z"
},
{
"id":"RU-ALT",
"title":"Altay",
"d":"M469.26,650.25L469.66,650.1L470.01,650.37L471.44,652.82L472.35,652.65L474.11,653.62L474.46,654.4L475.11,654.67L475.2,655.03L476.6,655.7L477.15,657.41L477.76,657.71L478.37,659.64L479.07,660.21L479.5,661.28L482.3,661.63L482.29,662.6L481.89,663.52L480.48,664.19L480.32,664.57L480.82,665.32L483.04,667.17L483.18,668.44L482.61,669.01L482.59,669.81L482.91,670.9L483.58,670.85L483.81,671.18L483.82,672.01L483.82,672.01L483,671.44L482.34,671.55L480.44,672.99L480.78,673.93L480.53,675.45L480.91,675.75L480.98,677.49L478.93,677.53L478.35,678.63L476.13,678.14L474.42,678.44L474.75,680.3L474.04,680.65L473.8,681.72L471.96,683.21L472.12,683.92L470.31,684.67L468.84,684.83L467.91,685.47L466.76,685.56L464.68,687.17L462.87,687.42L462.48,689.2L462.13,688.82L461.3,689.18L461.42,689.88L462.22,689.79L462.89,690.46L465.06,690.86L464.87,691.78L465.81,692.34L465.05,692.94L465.13,693.47L464.61,693.82L464.25,693.66L461.84,694.47L461.84,694.47L461.19,693.56L461.07,692.86L459.99,691.7L457.05,690.47L455.99,690.36L455.67,690.61L454.97,690.06L454.84,690.59L454.02,691.42L452.29,691.12L452.1,692.32L450.93,693.14L449.01,692.91L448.15,693.33L447.04,692.64L446.15,692.51L445.66,692.61L445.44,693.07L443.2,693.19L443.39,692.38L442.93,691.61L442.77,690.53L440.41,690.95L441,688.63L440.86,687.97L440.33,688.32L439.28,687.56L437.69,686.97L437.26,688.13L435.96,688.14L436.16,690.78L434.23,691.55L434.18,692.39L433.45,692.39L433.36,693.24L426.78,679.58L421.64,670.17L417.53,663.59L417.53,663.59L417.85,662.81L418.15,662.93L418.3,662.61L418.17,662.06L418.9,661.87L418.16,661.43L418.14,660.57L419.17,660.51L419.69,659.94L419.73,660.83L420.54,661.47L422.69,660.93L423.04,659.67L423.42,659.39L425.1,659.06L425.6,659.36L425.83,658.91L426.26,659.22L426.93,659.12L427.52,658.64L428.25,659.05L428.94,658.76L429.79,658.15L429.93,657.56L431.51,657.06L431.69,656.31L433.27,655.34L433.07,654.84L433.51,654.51L433.84,654.37L434.13,654.91L434.55,654.78L435.74,653.82L436.59,653.73L436.44,653.17L436.94,652.69L438.67,652.17L438.4,651.34L438.94,650.76L439.34,650.8L439.6,651.93L440.53,652.85L440.76,653.81L441.47,653.7L441.97,654.2L443.17,654.16L444,655L444.03,656.13L445.91,656.18L445.84,656.82L445.1,657.3L445.59,658.57L448.1,659.11L448.48,659.31L448.26,659.92L449.67,660.95L450.38,661.1L451.13,660.83L450.91,660.54L451.81,659.65L451.67,659.17L452.3,658.31L452.17,657.63L454.81,655.04L455.43,654.71L456.37,654.81L456.65,655.69L457.22,655.92L457.88,655.19L457.78,654.15L460.06,653.8L461.14,653.99L463.19,652.93L464.18,653.2L464.48,653.57L465.89,651.79L467.96,650.79L469.22,650.54z"
},
{
"id":"RU-AMU",
"title":"Amur",
"d":"M718.05,618.54L720.3,618.33L722.37,616.94L724.45,616.56L724.88,616.77L726.35,616.61L730.28,617.37L730.67,617.77L730.93,618.92L731.37,619.17L731.41,620.29L733.09,620.62L733.88,620.31L735.23,620.4L738.81,623.75L739.48,623.8L740.05,623.44L740.45,622.46L741.85,623.96L743.21,624.59L744.4,624.93L747.33,624.82L748.26,625.41L750.25,628.69L751.35,629.41L751.68,630.9L752.2,631.27L753.5,631.21L753.55,631.58L755.38,632.2L756.41,631.7L758.3,631.83L759.83,633.22L761.01,632.89L762.56,633.41L763.06,633.74L763.19,635.07L763.82,635.22L764.64,635.08L765.99,635.39L767.34,634.48L767.58,634.87L769,635.2L769.5,634.32L770.34,634.03L772.16,634.08L772.8,635.36L774.1,635.06L774.72,633.92L775.31,633.83L776,634.55L776.75,634.22L777.56,634.4L777.99,634.04L778.71,634.22L780.33,635.22L780.82,635.88L781.8,635.91L782.66,636.54L783.35,636.33L784.05,636.61L785.17,635.6L784.4,634.35L785.26,633.9L785.87,633.97L786.3,633.55L786.96,633.7L787.47,633.31L788.23,633.47L788.68,633.2L790.02,633.56L790.44,633.25L790.91,633.33L791.39,633.96L792.09,633.66L792.94,633.93L793.51,633.39L796.51,633.16L798.39,634.07L798.39,634.07L798.39,634.07L798.39,634.07L799.26,634.47L800.41,634.5L803.94,633.92L804.07,634.41L806.66,634.09L808.16,633.41L809.32,633.59L809.88,634.85L810.52,635.32L810.22,636.09L810.5,636.54L812.31,637.59L812.08,637.99L810.85,638.15L809.94,639.87L808.54,640.23L808.52,641.35L808.17,641.9L806.28,642.38L805.47,643.89L804.75,644.08L804.32,644.79L802.97,645.29L802.79,645.8L801.5,646.01L801.2,646.74L800.22,647.25L800.21,648.36L799.35,651.04L798.96,651.24L798.11,651.01L796.62,651.72L796.1,652.6L795.34,653.06L794.92,655.07L794.03,656.08L794.75,656.47L795.8,656.34L796.34,656.98L797.17,657.03L797.9,657.84L798.89,657.35L800.02,657.91L800.89,657.73L801.58,658.25L802.08,660.77L801.85,661.33L802.62,662.98L801.67,664.6L802.16,664.78L803.65,664.16L804.67,664.26L804.83,664.62L804.42,665.02L804.75,665.66L805.42,665.86L806.11,665.52L806.25,664.88L807.98,664.42L808.7,664.71L810.74,664.51L811.42,664.75L812.04,664.54L812.42,663.82L813.01,663.6L813.38,663.89L813.9,663.5L813.79,662.41L815.11,661.55L816.04,661.54L816.44,660.84L817.14,661L817.69,661.78L818.68,661.62L819.28,662.18L819.91,662.11L821.84,660.98L822.94,661L823.54,660.25L826.46,662.54L826.27,662.93L825.25,662.89L825.08,663.21L825.73,663.7L826.1,664.54L825.73,665.34L825.9,666.18L824.21,668.65L824.56,669.99L824.36,670.8L824.81,671.01L824.97,671.61L824.05,672.74L824.37,673.22L824.17,674.07L820.46,673.56L819.88,673.1L819.03,673.01L814.81,671.2L814.33,671.86L814.9,673.19L814.42,673.71L814.56,674.33L815.65,675.6L815.53,676.25L814.17,677.2L811.76,677.05L811.03,677.45L808.6,679.7L808.41,680.86L807.95,681.38L805.21,682.36L804.72,682.25L803.5,682.88L801.97,682.78L801.62,684.02L802.25,685.6L802.04,686.37L801.1,686.33L800.39,687.55L799.29,687.89L798.34,690.37L797.07,691.07L797.5,692.12L796.41,694.01L796.46,694.53L796.77,694.78L797.62,694.17L798.09,694.16L798.69,695.1L798.72,695.72L798.02,696.54L797.94,697.06L798.41,697.39L798.93,697.07L799.58,697.18L800.07,697.58L800.52,697.34L800.7,698.4L801.49,698.65L802.08,699.83L801.42,700.78L801.94,701.16L801.95,702.1L802.37,702.7L802.1,703.64L802.3,703.95L801.38,705.22L802.13,706.52L802.14,708.47L801.72,709.83L801.27,709.97L801.27,709.97L800.08,709.89L799.55,710.18L798.53,711.73L798.2,712.8L796.97,712.98L795.69,713.75L795.39,714.24L795.39,714.24L795.02,714.34L794.36,713.81L792.92,714.19L790.76,712.33L790.69,711.68L790.19,711.43L790.21,710.91L789.48,710.58L789.27,709.7L788.1,709.56L787.88,708.23L787.53,708.01L786.9,708.02L786.59,708.9L785.63,708.37L784.76,708.88L784.11,707.81L782.36,707.5L782.54,706.32L782.2,706.26L782.06,706.56L780.82,706.14L779.72,706.3L778.78,707.27L778.63,707.01L777.45,706.8L776.63,706L776.3,706.41L775.65,706.31L774.8,705.46L774.47,704.2L773.83,704.05L773.5,703.56L773.66,702.55L773.3,701.53L774.02,699.98L774.07,699.21L772.66,698.6L772.2,698.07L772.37,696.98L771.87,696.39L772.38,695.2L771.82,694.03L771.92,693.35L771.48,693.01L770.61,691.24L769.25,689.83L769.08,688.34L769.62,686.84L768.9,686.95L769.11,687.71L768.67,687.57L768.51,686.81L769.2,686.57L769.21,686.08L768.3,685.6L768.61,684.47L767.48,683.68L767.91,683.25L767.83,682.32L767.35,682.16L765.95,679.66L765.83,678.74L766.34,678.61L766.63,677.59L764.78,676.59L765.79,675.68L764.99,675.42L765.1,674.38L764.49,673.52L763.99,673.56L764.03,672.74L763.14,671.98L762.68,672.2L762.45,671.89L762.43,671.31L763.07,671.08L762.94,670.34L763.45,670.05L762.99,669.66L762.41,670.08L761.44,668.49L760.29,668.95L760.18,668.33L760.65,668.03L760.76,667.49L759.86,666.42L759.62,666.29L759.11,666.69L758.79,666.04L756.35,664.89L754.88,665.18L754.57,666.12L754.27,665.67L753.48,665.47L753.35,664.99L751.39,664.66L750.06,662.88L749.12,663.14L747.27,661.44L745.99,661.4L745.33,660.7L744.95,661.33L744.97,660.74L744.63,660.66L744.53,661.32L744.3,660.9L742.88,660.55L742.11,661.23L741.4,661.13L739.93,661.83L736.92,661.97L736.23,661.29L735.67,661.7L734.95,661.66L734.33,662.22L734.33,662.22L733.99,660.87L733.61,660.63L733.56,657.41L732.5,655.54L732.19,655.37L732,655.77L731.27,654.68L731.34,653.72L732.03,652.79L731.51,650.66L731.81,650.1L732.46,649.68L732.72,650.32L733.2,650.33L734.52,649.7L734.62,649.22L733.84,648.79L733.45,648.15L732.97,647L733.21,646.03L732.98,645.49L732.13,645.67L731.67,646.15L731.6,645.59L731.88,644.47L733.62,642.62L733.62,641.08L734.26,640.46L733.34,640.24L733.86,637.99L733.71,637.02L733.28,636.09L732.17,635.2L731.67,635.24L731.29,636.4L730.74,636.81L729.45,636.52L729.01,635.91L729.25,635.26L728.74,633.52L728.95,632.46L728.56,631.96L728.58,630.49L728.25,630.02L725.58,629.94L725.13,630.5L724.56,630.52L724.01,631.14L723.35,631.13L722.79,631.58L722.16,631.67L721.67,631.14L720.39,631.66L720.14,631.41L720.03,628.26L720.9,627.41L722.91,627.1L723.13,626.72L722.16,626.21L722.17,625.52L721.45,625.25L721.63,624.38L719.22,623.88L719.1,623.31L717.98,622.45L718.05,621.87L718.46,621.58L718.33,621.25L716.99,620.53L716.91,620.11L718.12,618.93z"
},
{
"id":"RU-ARK",
"title":"Arkhangel'sk",
"d":"M142.91,506.1l0.9,-0.1l0.79,-1.08l0.03,-0.9l0.65,0.56l1.3,0.44l0.5,0.97l1.2,-0.06l0.68,0.51l0.92,-0.04l-0.87,-2.3l0.02,-1.35l0.34,-0.32l-0.29,-0.35l-0.25,-2.22l-0.67,-0.92l0.05,-0.57l-1.17,-0.67l-0.74,-1.02l-0.2,-0.92l-2.14,-3.11l-0.07,-2.26l0.51,-1.91l0.71,-0.94l2.17,-1.07l2.08,-1.89l1.88,-3.12l3.51,-1.03l1.94,-1.23l1.94,-2.38l0.63,-1.33l0.67,-0.22l1.09,-2.71l1.13,-0.56l2.58,1.51l0.06,0.5l1.49,0.25l3.14,-0.3l0.6,1.44l1.65,0.54l0.67,1.01l-2.63,2.58l0.24,0.94l0.85,-1.65l1.77,-1.09l0.17,0.32l0.17,-0.26l0.62,0.09l0.9,1.67l0.75,0.48l-0.41,1.02l0.8,2.11l0.22,-0.7l-0.55,-1.07l0.57,-1.71l-0.59,-1.34l-0.15,-1.25l1.11,-3.05l0,0l1.72,0.44l1.3,1.82l3.98,1.13l2.96,2.15l0.54,0.08l1.26,-0.55l2.09,1.53l1.89,-0.8l5.21,4.21l2,-0.28l2.39,0.22l0.37,-0.34l-0.88,-1.48l0.71,-1.27l2.37,-2.12l1.62,-0.13l1.02,0.34l1.35,-0.13l1.91,0.38l0,0l0.5,1.49l-0.17,4.03l0.4,2.57l0.15,6.44l4.03,-0.79l0.62,2l2.05,4.15l0.84,1.05l1.38,0.65l0.95,0.07l-1.19,5.53l-2.84,-1.04l-2.2,-0.39l-1.15,2.24l-1.68,-0.51l-1.8,0.17l-0.7,2.17l-2.76,0.09l0.08,1.14l-0.33,0.79l-2.09,-0.5l-0.11,-1.69l-2.06,-0.36l-2.55,0.35l-1.69,-0.21l-4.78,0.38l-1.32,1.21l-0.97,0.03l-2.1,-0.6l-1.69,0.42l-1.97,1.22l1.05,2.38l0.88,0.96l1.04,0.54l1.38,-0.04l1.2,0.8l1.29,0.22l2.47,1.94l1.79,1.86l0.37,0.8l-0.12,1.47l-1.09,1.46l1.18,2.73l3.22,1.95l0.55,0.75l-0.77,1.44l-1.2,1.22l-1.72,1.09l1.22,3.56l-0.25,4.85l1.31,-0.01l0.19,1.98l1.58,0.04l0.36,-1.81l2.07,-0.18l2.45,0.24l0.01,-1.46l-0.61,-0.9l1.01,-3.8l2.01,-0.08l0.79,-1.65l6.16,1.04l-2.02,9.66l-0.48,0.13l-1.36,7.03l3.34,0.98l-1.91,6.45l-1.33,-0.25l-0.99,0.68l-1.11,-0.01l-1.81,1.29l-0.99,1.06l-0.32,1.99l0,0l-2.67,-0.47l-0.09,-1.58l-0.38,-0.36l-2.96,-0.81l-0.69,0.45l-1.43,-0.23l0.08,0.58l-0.45,0.56l-0.47,1.79l0,0l-1.85,-0.07l-0.52,-0.46l0.39,-0.9l-0.38,-0.23l-0.95,0.1l-1.09,-1.03l-1.03,0.94l-2.2,0.15l-1.94,-1.1l0.49,-1.94l-3.74,-0.51l-0.57,4.34l-6.97,-0.71l-0.55,-0.67l0.18,-0.27l-0.24,-0.37l-0.99,-0.05l-1.91,0.78l-0.12,0.84l-0.79,0.21l-0.91,1.05l-0.12,0.76l-0.97,0.26l-1.46,-0.63l-0.92,1.32l-1.12,-1.47l-0.97,-0.68l-0.67,0.18l-0.49,0.86l-0.42,-0.02l-0.72,0.64l-1.71,-0.97l-0.42,-0.81l-0.53,0.6l-1.43,-1.14l-0.42,1.2l-0.94,-0.48l-0.27,-0.67l-1.52,1.08l0.33,1l-0.62,0.87l-1.15,0.68l-1.4,-0.09l-1.88,-1.5l-0.83,0.4l-1.25,-0.59l-0.41,0.07l-0.48,1.06l-1.1,-0.18l-1.22,0.63l-0.97,-0.33l-0.72,-0.89l-0.94,-0.03l-0.85,0.95l-2.02,-0.3l-0.39,0.64l-1.58,-0.34l-0.77,-0.57l-1.16,0.08l-0.75,-1.37l-1.29,-0.43l0.14,-1.47l-0.24,-0.47l-0.63,0.87l-1.05,-0.57l0.4,-1.68l-0.38,-0.93l-0.82,-0.17l-0.44,-0.49l0.16,-0.63l-1.63,-2.89l0.15,-1.76l0,0l0.07,-2.11l0.96,-1.13l0.04,-0.32l-0.57,-0.59l0.7,-1.77l-0.04,-1.09l-0.73,-0.58l0.07,-0.79l-0.81,-1.99l-0.31,-0.32l-0.97,0.16l-0.64,-0.79l-0.07,-0.62l0.51,-0.03l0.55,-1.77l-0.1,-2.65l-0.82,-1.29l-0.71,-0.27l-2.03,0.36l-3.19,-1.95l-2.21,-3.17l-0.2,-1.79l0.9,-1.18l0.09,-0.58l-0.88,0.41l-0.24,-0.25l0.59,-0.78l-0.11,-0.52l-0.76,-0.78l-0.09,-1.29l-2.05,-2.89l1.35,0.21l0.57,-0.37l1.24,0.35l1.83,-2.62l-0.56,-2.02l0.19,-0.62l0,0l0.6,0.61l0.47,0.08l0.19,-0.25l0.63,0.48l0.53,-0.32l0.24,0.37l1.58,0.1l0.51,1.16l1.23,0.33l1.17,-0.46l0.19,-1.1l0.46,-0.32l0.6,0.24l0.79,-0.15l1.32,-1.69l-0.53,-2.27l-0.79,-1.04l0.54,-1.12l0.58,-0.31l-0.87,-0.22l-0.09,-0.3l0.9,-0.1l-0.6,-0.45l-1.21,-0.28l0.4,-1.27l-1.26,0.26l-0.51,0.85l0.13,0.38l-0.34,-0.4l-0.63,-0.03l-1.07,0.68l-1.62,-1.14l-2.85,-4.83l-1.23,-0.22l-0.25,-1.73l0.41,0.08l-0.73,-0.66l-0.18,-1.08l0.42,-0.24l0.5,0.6l0.39,-0.03l0.25,-0.49l1.15,-0.6l0.16,-3.2l1.26,-0.31l2.71,1.15l2.17,1.16l0.14,1.04l0.41,0.55l2.13,1.49l2.13,0.04l-0.23,0.82l-0.61,0.06l-0.22,0.42l-0.43,-0.34l-0.97,0.52l-0.06,0.62l0.82,0.79l-0.89,0.98l0.14,0.55l0.27,-0.12l0.04,-0.78l0.69,-0.16l0.11,-1.09l0.51,-0.01l0.62,-0.51l1.22,0.1l-0.69,-0.96l0.26,-0.27l1.05,0.64l2.35,0.59l1.46,1.17l1.37,0.36L142.91,506.1zM237.51,374.44l0.36,-0.06l0.69,0.59l1.16,1.92l0.03,0.7l0.56,0.15l-0.01,-0.35l0.32,-0.02l-0.01,1.01l0.46,0.43l-0.38,0.18l0.2,0.85l-0.6,0.78l0.18,0.62l-0.86,1.04l0.23,1.1l0.63,0.71l-0.84,0.26l-0.79,-2.19l-1.06,-0.71l-0.02,-1.1l-0.61,-0.68l-0.17,-1.08l-0.62,-0.6l-0.83,0.27l-0.59,-0.28l-0.15,0.26l-1.08,-1.67l0.55,-1.19l0.61,0l0.4,-0.47l0.6,0.15l0.35,-0.44l0.77,0.42L237.51,374.44zM254.97,327.28l0.25,0.76l1.17,0.64l2.05,-0.2l0.79,0.36l0.25,1.03l0.87,0.05l-0.21,1.31l0.39,-0.8l2.66,0.5l0.62,0.4l0.9,1.54l-0.12,1.13l-2.48,0.95l-2.27,0.22l-0.43,0.35l3.42,-0.11l0.88,0.52l-0.75,0.83l-1.39,-0.02l-2.72,1.17l-0.53,-0.28l-1.07,0.41l1.42,0.26l0.54,-0.29l0.6,0.38l2.17,-0.85l0.44,0.33l-0.33,0.83l0.11,1.43l-0.79,1.74l-0.67,0.17l-0.66,-0.64l-0.11,0.54l-0.27,-0.48l-0.37,-0.04l-0.21,0.16l0.47,0.26l-1.17,0.51l-1.65,-1.07l0.65,0.58l-0.69,0.52l0.89,-0.09l1.83,0.58l0.58,2.16l-1.37,-0.05l-0.58,-0.72l0.3,2.07l-0.16,-0.43l-0.25,0.14l0.14,1.58l-0.38,0.05l0.02,0.43l-0.67,-0.25l0.08,-0.44l-0.5,-0.36l-1.82,-0.57l-0.72,0.2l0.97,-0.07l1.59,0.86l0.19,0.32l-0.37,0.07l0.85,0.46l0.13,1.05l-1.34,0.61l-0.26,-0.22l-0.37,0.26l-1.09,-0.14l1.1,0.33l0.28,-0.21l0.6,0.54l0.37,-0.43l0.13,1.78l-1,1.76l0.34,0.38l-0.6,-0.11l1.13,0.25l-0.14,0.6l0.52,0.33l0.51,1.3l-0.94,0.86l-0.42,1.39l-0.43,0.27l0.84,0.22l-0.52,0.8l0.04,0.9l-0.33,-0.01l0.61,1.14l-1.01,-0.35l0.03,0.52l-0.96,0.38l0.35,0.18l0.73,-0.42l1.01,0.04l0.51,0.7l0.27,3.22l0.23,0.23l-0.23,0.36l0.52,0.8l0.12,1.37l0.58,0.98l-0.05,0.55l0.88,1.08l0.19,1.27l0.55,0.72l1.92,5.27l1.29,1.28l1.74,2.58l1.81,1.82l0.74,1.33l2.16,1.46l0.93,0.06l1.22,1.76l0.02,0.27l-0.41,-0.11l-0.19,0.81l-0.44,0.29l0.21,0.33l-0.69,0.7l0.23,0.55l-3.07,-1.62l-0.11,0.54l-0.9,-0.19l-0.19,-0.52l-0.44,-0.15l0.48,0.91l0.78,0.4l0.9,0.32l0.63,-0.24l1.04,0.99l0.05,0.44l-1.42,-0.25l-0.98,-0.66l-0.48,0.1l-0.28,-0.43l-0.96,-0.32l-0.8,-0.92l-0.32,0.14l0.73,0.77l-0.5,0.01l-0.52,-0.82l-0.1,-1.27l0.64,-0.04l-0.58,-0.49l-1.27,0.8l-0.89,-0.87l-0.24,0.39l0.92,0.73l-0.87,-0.17l-0.17,0.29l1,0.7l-0.53,0.37l1.05,0.21l0.38,-0.22l-0.67,-0.2l-0.03,-0.42l0.63,0.05l0.65,0.72l-0.44,0.16l0.04,0.3l0.48,-0.01l0.79,0.88l-0.48,0.01l0.03,-0.32l-0.39,-0.17l-0.94,0.45l-2.09,-1.85l-0.52,-0.16l0.28,0.38l-0.44,0.17l-1.41,-0.85l0.43,0.59l-0.15,0.22l1.27,1.03l0,0.57l-0.54,-0.42l-0.43,0.24l-0.41,-0.75l-0.21,0.27l-0.61,-0.22l-0.99,-1.52l-0.76,-0.48l-0.32,-0.88l-0.58,0.64l1.08,1.6l-0.33,0.3l-0.18,-0.57l-1,-0.76l-0.04,0.51l-0.35,0.07l0.72,1.15l-0.29,0.04l-0.06,0.54l-0.56,0.1l-0.04,0.53l-0.84,-0.56l-0.7,-1.13l-0.53,-0.06l-0.26,-0.44l-0.39,0.19l-0.84,-1.26l-0.09,-0.4l0.31,-0.27l-1.16,-0.84l-0.74,-0.2l0.33,0.74l-0.57,0.45l-1.09,-1.06l-0.23,0.3l0.55,0.63l-0.41,-0.13l-0.29,0.29l-0.88,-0.45l0.07,0.37l-0.79,-0.19l-0.63,-1.02l-0.21,0.41l-0.31,-0.46l-0.6,0.11l-1.39,-0.96l-0.33,0.06l0.4,0.42l-0.18,0.26l-1.47,-1.73l0.4,0.15l1.25,-0.56l0.77,0.11l0.67,-1.27l-1.73,-2.55l1.03,-0.18l0.29,-0.43l1.76,1.46l-0.38,-1.27l-0.67,-0.94l0.47,0.24l0.17,-0.39l0.51,-0.05l0.76,-1.06l-0.24,-0.87l-0.57,1.3l-0.62,-0.35l-0.11,-0.42l-0.32,0.03l0.02,1.15l-0.7,-0.42l0.03,-0.63l-0.34,0.16l-0.77,-0.32l-0.37,-0.58l-1.32,-2.54l0.03,-1.19l-0.5,-1.44l0.7,-0.41l0.1,-0.85l0.48,-0.76l-0.35,-0.35l-0.58,0.33l-1.2,2.06l0.07,0.79l-0.44,-0.62l-0.57,0.22l-0.09,-0.63l-0.51,-0.37l-0.08,0.5l0.72,0.99l-0.56,0.73l-1.36,-1.35l-1.25,-3.38l0.25,-0.32l-0.55,-1.47l-0.34,0.04l0.21,2.15l-0.31,0.67l-0.62,-0.32l0.41,1.95l-0.95,-1.15l-0.4,-1.96l-0.03,0.83l-0.23,0.42l-0.27,-0.05l-0.13,0.52l0.83,1.3l-0.87,-0.23l-0.56,0.42l-1.07,-0.25l-0.3,0.2l-0.98,-1.27l-1.01,-0.48l-0.38,-0.96l0.05,-0.95l-1.04,-3.97l1.05,-6.13l1.54,-1.24l0.52,-0.87l0.61,1.13l0.87,0.28l0.42,-0.09l0.64,-0.8l0.66,1.67l0.46,0.14l0.43,-0.48l-0.21,-1.72l0.29,-0.47l0.46,0.19l-0.61,-1.33l0.49,0.04l0.42,-0.42l-0.45,-0.07l-0.27,-0.93l1.39,0.8l-0.31,-1.1l0.26,0.24l0.5,-0.29l0.13,-0.61l-1.04,-0.67l-0.04,-0.44l0.68,0.17l0.63,0.75l-0.32,-0.82l0.29,-0.73l-0.45,-0.57l0.79,-0.81l-0.28,-0.21l-0.49,0.33l0.11,-0.71l1.25,-0.56l-0.17,-0.43l0.74,-0.66l-0.46,-0.4l0.52,-0.37l1.03,-0.15l0.97,0.62l0.25,-0.27l-0.96,-0.58l-1.2,-0.01l-1.41,1.13l-0.41,-0.12l0.88,-1.48l-0.2,-0.27l-0.5,0.38l-0.36,-0.4l0.57,-0.41l0.43,0.2l0.5,-0.49l-0.43,-0.56l-0.24,0.6l-1.78,-0.29l-0.78,-1.22l-0.44,-0.15l1.23,-3.19l2.56,-1.44l2.26,0.96l1.51,0.03l-1.15,-0.74l-0.02,-0.3l-0.71,-0.04l-0.76,-0.49l-0.15,-0.46l0.3,-1.34l0.49,0.04l0.2,-0.29l0.59,0.55l0.48,0.01l0.18,-0.48l-0.64,-0.23l-0.85,-1.19l0.15,-0.41l-0.27,-0.23l0.29,-0.45l-0.12,-0.51l1.78,-2.33l0.32,-0.14l0.62,0.32l0.94,-1.06l1.44,-0.68l0.44,0.5l0.51,-0.37l-0.14,0.63l0.21,0.13l1.27,0.09l0.43,-0.69l0.8,-0.23l0.71,0.64l0.2,-0.18l-0.73,-0.8l0.3,-0.95l0.91,-0.81l0.65,0.1l0.68,-0.87l1.1,-0.56L254.97,327.28zM294.61,256.23l0.34,0.03l0.09,-1.29l0.39,-0.57l1.77,-0.3l0.66,-1.36l-0.18,-0.86l-1.23,0.17l-0.38,-0.43l0.65,-1.41l-0.29,-1.4l1.23,-1.04l0.29,0.13l-0.19,0.39l1.78,-0.63l1.24,0.09l0.56,-0.8l0.92,0.86l0.81,-0.53l0.26,0.82l2.22,0.38l0.41,-0.28l0.61,0.09l-0.07,2.18l0.58,-0.09l0.41,0.54l0.4,-1.49l0.54,0.53l0.35,-0.6l-0.16,-0.45l0.4,0.07l-0.14,-0.44l0.29,-0.5l0.58,0.54l-0.15,0.78l0.45,-0.14l0.36,0.32l-0.12,0.34l0.73,0.31l0.57,-0.85l0.5,-0.08l0.91,-1.06l1.88,-0.83l-0.31,-0.37l1.29,-0.79l0.49,0.21l0.94,-0.32l0.82,0.91l0.46,0.12l0.75,-0.62l0.19,-0.56l0.84,-0.55l0.7,0.35l0.39,-1.38l0.67,0.7l0.68,0.04l0.58,0.48l-0.73,-1.27l0.48,-1.42l0.62,0.2l0.2,-0.31l-0.27,-0.37l0.13,-0.55l0.85,-0.59l1.05,0.07l0.35,0.93l0.82,-0.41l0.03,-0.61l0.78,-0.25l0.26,-1.61l0.64,-0.56l0.6,-0.06l0.48,0.7l2.33,1.2l0.41,-0.06l0.42,-0.43l-0.66,-1.12l-0.09,-1.17l-1.12,-1.64l0.43,-1.65l0.75,-1.05l0.59,-0.32l0.54,0.28l0.97,-1.46l0.62,-0.08l0.7,-1.45l0.85,-0.63l0.69,-0.09l0.36,-0.82l1.6,-0.54l0.05,-0.76l0.76,-0.71l1.06,0.52l2.48,-2.03l2.75,-0.34l1.4,0.28l0.63,0.86l0.71,-0.19l0.42,0.41l0.74,-0.05l0.49,1.41l0.59,-0.35l0.28,0.8l1.29,1.05l-0.43,1.56l0.51,0.87l0.82,0.13l-0.14,1.71l0.92,0.85l-1.56,2.2l-0.37,2.33l0.72,0.61l-1.13,1.34l-1.16,2.68l-1.09,0.53l0.21,0.54l-0.91,1.61l-0.92,0.64l0.06,0.53l0.73,0.47l-0.16,0.43l-0.77,0.27l-0.58,-0.22l-1.23,0.55l-2.73,2.06l-0.84,0.33l-2.7,2.51l-0.75,0.04l-1.82,0.82l-1.7,1.64l-0.63,0.13l-0.6,-0.38l-0.01,0.57l-1.24,0.95l-1.24,0.19l-2.78,1.19l-0.17,0.48l-2.32,1.37l-0.29,0.88l-0.43,-0.08l-0.76,0.5l-0.91,-0.18l-0.06,0.34l-1.1,0.21l-0.83,0.76l-2,0.88l-1.61,0.15l-1.08,1.16l-0.82,0.11l-0.64,1.37l-0.29,-0.4l0.46,-0.79l-0.66,-0.36l0.08,-0.74l-0.42,-0.37l-0.2,1.33l-0.79,0.76l-0.3,0.81l-0.72,0.28l-0.31,0.55l-0.73,0.05l-0.02,0.26l-1.12,-0.64l-0.31,1.01l-1.33,1.45l-1.76,0.48l-1.6,1.22l-0.38,0.62l-0.5,0.11l0.33,-0.4l-0.26,-0.34l-0.55,0.28l-1.04,-0.04l-1.3,2.39l-0.23,0.98l-0.08,-1.47l-0.45,0.08l-0.4,1.39l0.19,0.83l-0.45,0.29l0.05,0.59l-0.46,0.06l-0.37,0.97l-0.55,0.39l-0.39,-0.59l0.17,-2.3l-0.59,-0.15l-0.24,0.58l0.36,0.29l-0.66,0.77l-0.55,1.74l-0.62,0.64l-0.76,0.26l-0.07,0.49l-0.92,0.26l-0.27,0.5l0.22,0.63l-0.39,0.3l0.38,0.36l-0.56,1.74L294.1,284l-0.32,-1.04l0.16,-1.01l-0.67,-0.05l-0.18,0.74l-0.38,0.01l0.23,0.27l-0.69,0.24l0.4,0.39l-0.17,0.97l-1.39,0.79l0.18,-0.23l-0.4,-0.59l-0.22,0.75l-1.01,-0.53l-0.34,0.29l0.8,0.83l0.87,0.35l2.63,-0.21l0.48,0.96l-0.67,1.73l-0.37,0.22l-2.06,-0.12l-0.42,-0.46l0.5,1.89l0.67,0.29l-0.16,1.13l-1.08,0.67l-1.21,0.14l-1.68,-0.58l-0.58,0.27l-0.44,-1.09l-0.73,-0.82l-0.34,-0.01l0.96,1.39l-0.11,0.58l1.1,0.32l0.21,0.83l0.51,0.25l0.24,1.69l-0.53,0.35l-0.18,0.56l-1.15,-0.02l-1.98,-2.83l-0.68,-0.11l-0.37,-0.41l-0.2,-1.1l-0.54,0.26l0.31,1.35l1.12,1.64l-0.79,-0.17l-0.17,0.27l0.18,0.82l-0.56,1.47l0.28,0.78l-0.41,1.02l0.38,0.3l0.13,0.77l-0.47,0.07l-1.83,-0.73l-0.85,-1.22l-0.92,-0.25l-2.27,-1.65l-0.29,0.86l1.11,0.82l0.62,0.04l1.28,2.69l-0.3,0.71l0.57,1.28l-0.39,0.72l0.67,1.17l-0.67,0.31l0.73,0.52l-1.08,0.21l-0.22,-0.28l-0.09,0.47l0.68,-0.01l0.17,0.46l-1.07,-0.23l-0.32,0.32l0.56,0.21l-0.11,0.96l-0.93,-1.08l-1.01,-0.19l0.49,1.36l1.41,0.3l0.03,0.56l-0.35,-0.39l-0.81,-0.06l-0.23,0.22l0.22,0.47l-0.17,0.58l-0.39,-0.21l0.26,-0.56l-0.17,-0.39l-1.27,-0.69l-0.06,0.61l0.7,0.74l-0.13,1.21l0.69,1.26l-0.75,0.05l-0.05,0.53l-1.69,-0.61l-0.99,-1l-0.54,-0.13l-0.49,-1.88l-1.22,-1.96l-0.52,0.48l0.88,2.39l-0.39,0.22l-0.83,-0.35l-1.23,0.19l0.46,0.33l0.85,-0.16l0.94,0.38l0.26,-0.19l2.5,4.16l-0.21,0.36l-0.17,-0.23l-0.65,0.37l0.87,0.44l0.19,2.48l-0.62,0.85l-0.97,0.59l-0.52,-1.77l-0.75,-0.94l-3.81,-1l-1.31,0.12l-0.61,-0.96l-0.78,0.21l1.23,1.02l1.13,-0.03l2.11,1.03l0.76,-0.04l0.64,0.71l-0.14,0.39l0.84,0.37l0.76,2.89l-0.08,0.89l-0.68,0.6l-1.11,0.22l-0.04,0.78l-1.37,-0.43l-1.43,-0.81l-1.14,-2.33l-1.31,-1.06l-1.47,-0.47l1.94,1.15l0.69,0.79l-0.15,0.61l1.04,1.08l-1.23,0.38l1.25,0.02l2.35,2.49l0.04,0.89l-0.63,0.54l-0.1,0.67l-1.66,2.69l-0.66,-1.56l-0.61,0.23l0.35,0.95l0.28,-0.05l-0.62,1.36l0.15,0.47l-0.44,0.12l-2.32,-0.81l-1.66,-0.02l-0.38,-0.68l-0.02,-1.9l-1.52,-2.06l-0.35,-1.37l-0.35,-0.33l0.51,1.73l0.82,1.07l-0.06,2.65l-1.46,-1.04l-2.42,0.25l-0.77,-0.51l-0.53,-1.08l-1.04,-0.77l-1.22,-0.43l-1.42,0.54l-0.87,0.86l-0.55,-0.09l-1.26,1.51l-1.05,0.38l-0.19,-0.57l-0.77,-0.09l-0.18,-0.59l0.71,-0.96l1.02,0.02l0.53,-1.13l1.13,-0.77l0.04,-0.46l-1.37,0.96l-0.75,-0.75l1.25,-1.98l2.2,-1.29l0.3,-0.68l1.32,-0.15l1.49,-1.08l0.99,0.01l0.12,-0.39l0.41,-0.08l-0.13,-0.25l-0.56,0.45l-1.81,0.07l-0.72,0.72l-0.37,-0.46l0.5,-0.76l-1.17,0.78l-1.03,-0.25l-2.47,2.4l-0.85,-0.52l-0.48,0.42l-0.68,-0.42l0.07,-0.49l-0.42,-0.19l-0.4,-0.91l-1.28,-0.98l-0.33,-0.68l0.31,-1.1l0.26,0.61l1.41,0.06l1.06,-1.3l-0.23,-0.33l0.25,-0.46l1.28,-1.43l0.9,-0.56l1.61,-0.24l0.6,-0.65l1.19,0.44l0.29,0.86l1.16,0.11l-1.22,-0.61l0.34,-0.3l-0.38,-0.82l-1.99,-0.65l0.07,-0.61l3.08,-3.54l0.34,0.32l0.7,-0.45l1.34,1.01l1.57,0.06l0.4,0.36l-0.18,0.28l0.79,-0.16l0.5,0.36l0.04,0.46l0.58,0.01l0.88,0.84l1.67,-0.18l0.13,-0.22l-0.61,-0.11l-0.87,0.27l-1.24,-0.87l-0.1,-0.33l0.79,-0.35l0.43,-1.1l-0.56,0.9l-0.54,0.12l-0.5,-0.45l-1.21,-0.29l0.16,-0.34l-0.46,-0.89l-0.69,-0.05l-0.25,-0.4l-0.92,-0.36l-1.27,-0.15l-0.36,-0.59l0.42,-0.81l0.65,-0.43l0.15,0.99l2.5,-0.81l0.44,0.82l0.42,-0.31l0.1,-0.53l-0.63,-0.93l-0.57,0.29l-0.3,-1.04l-0.49,0.23l-1.43,-0.33l0.45,-1.62l0.85,0.14l1.11,-0.76l1.88,0.04l1.55,-0.6l0.28,-0.42l-1.06,-0.29l0.37,-0.44l-0.2,-0.64l-1.41,-0.2l-0.94,0.53l-0.11,-0.69l-1,-0.39l0.38,-1.11l-0.07,-1.03l1.7,-1.53l0.4,0.4l0.37,-0.11l-0.17,0.44l0.35,0.26l0.59,-0.06l0.13,-0.49l1.81,-0.59l0.84,-0.66l0,0.4l1.51,1.26l1.3,-0.03l0.19,-0.49l0.72,0.09l0.21,-0.24l-0.57,-0.74l-0.8,0.62l-1.06,-0.02l-0.49,-1.25l-0.4,-0.26l-0.39,0.24l0.05,-0.63l0.77,-0.37l-0.23,-0.38l-1.02,0.24l-0.42,-0.38l-0.94,0.11l-0.53,0.34l-0.34,-0.15l-0.28,0.37l-0.53,-0.04l-0.6,-0.64l0.03,-0.58l0.94,-1.03l2.45,-1.49l0.68,0.3l0.93,-0.93l0.76,-0.03l0.28,-0.35l-0.92,-0.49l-0.66,0.03l-0.52,0.76l-0.61,0.27l0.35,-0.78l-0.61,0.14l0.01,-0.27l1.04,-0.93l-0.58,-1.06l-1.97,0.72l-0.59,0.83l-0.86,0.07l0.14,-1.56l0.43,-0.96l-0.93,-0.72l-0.47,0.26l0.37,-1.79l0.59,-1.01l1.03,-0.67l0.07,0.72l0.97,-0.35l-0.24,0.56l0.33,0.36l0.89,-0.62l1.05,3.34l0.44,-0.54l0.67,-0.19l-0.09,-1.42l0.78,-0.64l0.41,-1.2l0.67,-0.16l0.46,-1.19l-0.61,-0.73l-0.78,-0.04l-0.15,-0.75l1.72,-1.91l0.54,-0.29l1.61,0.56l0.89,-0.3l-0.12,0.63l1.37,0.94l2.22,-0.15l-0.14,-0.93l-0.92,0.01l-0.19,-0.73l0.21,-1.02l-0.52,-0.97l-0.51,0.02l-0.14,-1.25l0.35,-0.57l1.82,-0.78l0.65,-0.65l0.92,-0.23l0.18,0.19l0.9,-0.77l-0.16,-1.18l-1.24,0.43l-0.49,-0.39l-0.2,0.18l-0.08,-0.39l0.75,-1l0.18,0.29l0.65,-0.41l0.47,0.13l3.03,-1.64l-0.04,-1.04l-0.63,0.09l0.62,-0.73l0.68,-0.17l-0.19,-0.64l1.07,-1.28l0.52,-0.2l1.45,0.43l0.45,-0.89l1.2,-0.1l-0.17,-1.26l1.09,-0.18l1.56,0.71l0.73,-0.77l1.16,-0.17l0,-0.65l0.29,-0.27l1.23,0.11l0.86,-0.35l0.33,-0.54l-0.22,-0.3l-0.65,-0.63l-0.96,-0.13l-0.18,-0.57l1.37,-1.44l1.79,-0.85l0.82,0.33l1.28,-0.01l-1.06,1.16l-0.87,1.63l-0.74,0.53l0.31,0.12l0.15,0.66l0.54,-0.35l0.71,0.29L294.61,256.23zM289.15,116.65l0.35,0.05l-0.05,0.27l-1.11,0.66l-0.98,1.6l-1.4,0.01l-0.38,0.89l-0.78,0.15l-0.4,-1.04l-0.85,-0.5l-0.27,-0.53l-1.57,-1.35l-1,-0.21l0.16,-0.52l2.58,-2.18l2.09,-0.89l1.42,0.24l1,0.55L289.15,116.65zM226.58,114.49l0.46,0.08l-0.74,2.77l1.31,1.45l-0.08,0.51l0.41,0.67l-0.3,0.33l-2.04,0.19l-2.53,-0.82l-1.48,0.16l-1.06,-0.46l-0.12,-0.9l-0.92,0.63l-1.19,-0.09l-0.23,-0.4l0.25,-0.59l1.44,-1.1l0.6,0.3l0.27,0.81l0.33,-0.06l0.88,-0.86l0.9,-2.35l1.72,-1.14l0.21,-1.3l1.15,0.86l0.01,0.51L226.58,114.49zM220.08,111.26l-1.48,0.08l-0.27,1.11l0.41,1.7l-0.72,0.69l-0.56,-0.07l-0.6,-0.37l-0.2,-1.43l-1.95,-2.05l-0.25,-0.87l0.57,-0.92l1.73,-1.39l1.71,-0.56l1.2,0.39l0.78,1.12l0.05,1.23l-0.65,0.71L220.08,111.26zM256.61,103.42l0.65,0.05l0.27,0.36l-0.4,2.02l-1.03,0.56l-0.6,0.92l-1.15,0.43l-1.11,-1.34l0.08,-0.25l0.28,-0.19l0.74,0.3l0.06,-0.84l0.91,-0.28l-0.8,-1.07l0.87,-0.77l1.02,-0.65L256.61,103.42zM267.9,101.94l0.16,0.73l1.03,0.73l0.23,0.56l-0.63,3.54l0.69,1.03l-0.86,0.87l-0.06,2.57l0.26,0.52l-0.45,1.55l-0.25,0.26l-1.26,-0.12l-0.54,0.19l-0.06,0.4l-1.81,-0.75l-2.03,0.34l-2.75,-1.3l2.22,-3.79l-0.72,-2.09l0.09,-1.15l-0.84,-1.99l0.81,-0.75l2.05,-0.59l1.15,0.15l0.64,0.91l0.46,0.02l0.29,-0.3l0.08,-1.5L267.9,101.94zM241.98,100.71l0.31,0.51l-0.36,1.18l4.05,4.64l-1.06,1.83l-0.63,-0.91l-0.8,0.4l-0.32,0.5l-0.07,1.83l-0.57,0.47l-0.52,-0.03l-0.74,-0.72l-4.02,-0.05l-2.38,-1.54l-1.04,-1.54l-0.12,-1.16l0.73,-0.46l2.01,0.14l0.44,-1.2l1.19,-0.2l0.42,-1.47l-0.96,-0.39l-0.13,-0.32l1.25,-1.43l0.79,-0.45l0.95,0.63l0.82,-0.73L241.98,100.71zM251.44,101.92l-0.57,0l-0.17,-0.55l2.31,-1.47l-0.77,1.7L251.44,101.92zM275.61,96.53l0.57,0.53l1.01,-0.1l4.7,2.25l0.86,1.27l0.63,0.39l1.1,2.32l-0.31,0.49l-2.47,-0.04l-1.89,-0.72l-0.28,1.05l-1.06,-0.12l-0.85,1.03l-1.31,0.75l-0.43,1.68l1.22,-0.04l1.19,0.65l0.27,0.48l-0.53,1.04l0.23,1.26l-3.08,-0.76l-0.27,0.3l0.74,1.77l-0.26,1.13l-1.38,-0.34l-1.48,-1.01l-0.45,-0.65l-1.71,-0.84l-0.69,-6.85l0.29,-1.34l-0.52,-0.94l-0.08,-1.29l-1.46,-2.06l2.25,-0.5l0.51,-0.44l1.36,0.39l0.35,-0.53L275.61,96.53zM250.16,100.86l-0.59,-0.38l0.21,-1.85l0.86,-1.32l0.27,-1.02l0.71,0.37l0.84,1.99l-0.5,1.5L250.16,100.86zM249.01,95.75l0.82,0.13l0.43,0.7l-0.03,0.36l-1.02,0.76l-0.37,1.58l-0.54,-0.09l-1.23,-1.16l-1.49,-0.28l0.02,-2.1l0.53,-0.99l-1,-1.9l0.6,-1.5l0.97,0.02l1.63,0.62l-0.01,0.72l-0.62,0.3l-0.42,0.82l1.81,0.59l0.26,0.58l-0.55,0.66L249.01,95.75zM274.32,90.22l0.51,0.11l0.63,-0.44l0.19,0.67l-1.35,3.62l-0.94,0.09l-0.37,-0.5L272.41,94l-0.28,0.52l-1.98,-1.67l-0.24,-1.23l0.47,-0.1l0.35,-0.63l2.69,-0.65l0.45,-0.52L274.32,90.22zM242.08,90.33l0.2,2.95l0.93,1.61l-0.87,1.94l-0.88,-0.72l-0.72,-1.35l0.3,-2.19l0.48,-0.77l-1.88,-1.32l0.8,-0.38l-0.13,-0.85l0.23,-0.15l0.72,0.31L242.08,90.33zM264.23,84.03l2.91,2l0.83,1.87l-0.72,2.13l-1.35,0.81l-1.16,-0.13l-1.08,0.75l-0.4,-0.24l-0.23,-1.21l-1.91,1.13l-3.07,-0.76l-0.45,-0.46l1.31,-2.4l-0.37,-0.36l-1.79,0.44l-0.25,-0.2l0.55,-0.8l1.83,-0.53l0.5,-0.97l0.84,-0.5L264.23,84.03zM200.93,80.65l2.02,1.72l1.27,-0.53l0.42,0.16l0.7,-0.51l1.56,0.85l0.71,1.02l0.11,1.22l-1.09,0.36l0.01,0.44l0.9,0.6l0.41,1.04l-0.21,0.72l0.79,0.4l0.44,0.65l-0.7,1.5l-0.36,0.09l-0.47,-0.39l-0.57,0.13l-0.2,-0.87l-0.39,-0.26l-1.12,0.24L204.34,89l-0.91,-1.12l0.12,-2.15l-0.96,0.34l-0.17,-1.91l-0.68,-0.53L201,83.67l-0.83,0.74l0.52,1.08l-1.06,-0.47l-0.24,0.25l0.12,0.99l0.48,0.2l0.1,1.35l-2.04,-0.5l0.02,1.81l0.36,0.24l0.06,0.67l0.58,0.47l-0.01,1.27l-0.95,-0.09l-1.11,-0.73l-1.46,1.6l-0.34,1.65l-1.2,-0.17l-0.69,-0.54l-0.52,0.8l0.36,1.65l-0.74,-0.44l-0.78,0.14l0.06,1.68l-0.72,0.66l-0.79,0l-1.05,-0.52l0.53,-2.58l-0.2,-1.69l-1.03,0.07l-0.61,0.66l-0.56,-0.44l-0.43,0.07l-0.42,1.36l-0.61,0.24l-1,-1.78l-1.04,-0.66l-1.62,-0.32l-0.59,-0.78l-0.56,-0.23l0.94,-0.96l1.72,-0.2l0.43,-0.53l1.5,-0.67l4.22,-0.65l1.75,-1.06l0.92,-1.04l-0.1,-0.34l3.09,-1.07l0.85,-1.4l1.54,-0.69l-0.62,-1.19l0.2,-1.03l1.08,0.18l0.79,-0.83L200.93,80.65zM304.73,81.03l0.56,2.73l-0.04,2.76L305,88.47l-0.6,0.48L304,89.98l-0.06,0.98l0.31,0.6l-1.41,1.21l-1.56,0.33l-0.49,2.18l0.39,1.59l-0.81,0.56l-1.63,0.32l0.86,0.28l-0.93,2.45l-0.79,0.33l-0.48,0.64l-2.28,-0.67l-1.46,-0.73l-0.59,-1.16l-1.17,-1.26l-1.17,0.3l0.1,0.53l-0.35,0.42l-0.57,0.02l-2.79,1.73l-1.16,-3.05l-0.65,-0.41l-0.68,-1.01l0.94,-1.54l-0.61,-1.04l0.14,-2.25l-0.34,-0.52l0.7,-0.37l-0.29,-0.79l0.42,-2.51l0.55,-1.25l0.9,-0.96l-0.55,-1.45l0.02,-0.25l0.43,0.24l-0.16,-0.64l1.01,-0.9l0.78,-0.08l1.38,-0.81l1.6,0.77l-0.75,0.59l-1.42,0.19l0,0.36l2.06,-0.45l0.9,0.94l1.8,-0.91l0.55,0.41l0,-0.37l0.5,-0.36l1.51,-0.27l1.52,-0.84l0.88,0.48l1.78,-2.15l3.15,0.18L304.73,81.03zM255.77,80.46l0.27,0.36l0.95,0.22l1.28,1.26l1.08,0.17l1.13,1.3l-4.25,1.54l-1.61,-0.26l-1.33,1.26l-0.57,-0.09l-1.27,-1.07l0.15,-1.52l-0.28,-0.41l-1.49,-0.19l-1.42,0.47l-1.66,-1.26l-0.09,-0.95l0.79,-1.13l1.33,-0.65l0.33,-0.05l0.68,0.59l0.95,-0.74l1.14,-0.11l0.4,0.22l-0.27,0.88l0.25,0.18l0.77,-0.31l0.37,-1.21l0.8,-0.09l0.75,0.19l0.74,0.75L255.77,80.46zM281.38,79.14l0.95,2.21l-0.46,2.8l-1.57,0.17l-1.62,1.48l-1.26,-0.27l-1,-1.07l-0.7,0.17l-1.53,-0.91l-0.21,-1.05l1.25,-0.41l1.25,-2.32l0.94,-0.53l3.01,-0.59L281.38,79.14zM224.68,79.93l-1.1,0.74l-1.15,0.16l0.33,0.6l-0.3,0.24l-1.46,0.1l-0.15,0.47l0.87,-0.08l0,0.32l-1.1,0.84l-0.02,0.55l-0.49,-0.12l-0.89,0.78l0.5,0.12l0.6,0.91l0.58,0.18l1.56,-1.99l0.56,0.81l0.58,-1.37l0.82,-0.29l0.48,0.99l0.81,0.03v-0.96l1.02,-0.65l1.66,1.78l0.05,0.77l0.69,0.05l1.48,1.21l-0.14,0.48l-2.72,3.11l-1.7,0.59l-0.24,1.5l-1.04,1.68l-1.5,0.78l-4.04,0.39l-1.54,1.1l-1.14,0.46h-1.08l-0.22,0.72l0.94,1.15l0.1,2.26l-0.4,0.82l-0.37,0.02l-0.53,0.67l-0.64,0.25l-1.23,-0.19l-1.65,-0.88l-1.23,0.14l-0.61,-0.61l-0.7,0.41l0.2,1.8l-0.69,0.26l-0.67,-0.14l-0.62,0.58l0.03,1.73l0.52,-0.43l0.55,0.31l1.49,-0.22l0.5,0.63l-0.19,0.8l0.45,0.47l-1.06,1.01l0.85,0.67l0.71,0.15l0.34,0.97l-0.59,0.47l-0.91,-0.06l-0.1,0.46l0.27,0.29l-0.72,-0.03l-1.37,-0.79l-0.33,-0.96l-0.64,-0.27l-0.44,0.98l0.57,1.86l-1.16,1.99l-0.61,-1.68l-1.01,-0.19l-1.09,0.86l-0.03,0.43l0.36,0.2l-0.16,0.67l-2.19,0.69l-0.34,-1.26l1.43,-3.43l1.22,-0.38l0.95,-0.89l-2.33,-0.17l0.15,-0.53l0.96,-0.49l0.01,-0.8l-0.93,-0.21l-0.87,0.65l-0.76,-0.16l-0.19,0.51l-0.58,-0.41l-0.15,0.5l-0.83,-0.11l-0.17,0.29l0.72,1l-0.08,0.4l-0.93,-0.17l-0.93,1.11l-0.54,-0.01l-1.23,-1.1l0.45,-1.44l-1.89,-2.63l0.08,-1.35l1.33,-0.82l0.69,-1.24l1.29,-0.6l0.75,0.7l-0.35,2.09l0.34,0.15l0.93,-0.55l0.63,-0.03l0.36,1.1l1.01,-0.55l0.37,0.52l2,-0.15l-1.16,-0.86l-0.09,-0.45l1.66,-0.04l0.16,-0.23l-2.73,-0.69l-0.64,-0.6l-0.45,-1.12l1.19,-0.5l1.37,0.33l0.92,-0.56l1.72,0.76l0.02,-0.65l-1.05,-0.83l0.35,-0.7l-0.25,-0.33l-2.38,-0.46l-2.6,0.73l-0.64,-0.42l2.56,-1.89l1.27,-1.35l0.88,-0.43l0.69,0.57l1.17,-0.93l1.16,0.12l-0.04,0.4l0.59,0.29l-0.17,0.99l0.29,0.18l0.52,-0.27l0.6,1.07l0.92,-0.2l-0.13,-1.5l1.01,0l1.12,0.42l0.41,-0.3l0.13,-0.49l-0.29,-0.72l0.47,-0.57l-0.13,-1.09l0.75,-0.37l0.29,0.18l0.35,-0.35l-1.07,-1.47l1.07,-0.63l0.73,0.29l0.3,-0.18l0.8,-0.98l-0.35,-0.47l0.28,-0.55l-0.49,0l0.25,-0.68l-0.24,-0.6l-2.79,0.95l-0.01,-0.89l0.91,-1.4l-0.31,-0.16l-0.61,0.66l-0.46,-0.17l-0.24,0.97l-0.33,0.09l-0.62,-1.04l1.19,-0.69l0.18,-0.73l-0.37,-0.31l-0.84,0.1l2.46,-1.78l0.77,-0.08l0.4,-0.73l0.95,-0.66l1.14,-2.64l2.94,-1.78l0.68,0.67l0.92,0.23l-0.38,0.54l-1.52,0.34l-1.82,1.13l0.55,-0.01l-0.15,0.48l0.63,0.06l0.26,0.92l0.67,-0.21l0.28,-0.9l2.53,-0.94l1.95,-2.44l1.02,3.65L224.68,79.93zM277.4,69.77l0.4,0.05l0.4,0.91l1.74,1.3l0.54,0.96l-0.85,1.88l-0.05,1.08l-0.75,0.47l-1.4,-0.2l-1.95,-3.15l-1.02,-0.88l-0.42,-0.84l0.1,-0.36l0.93,-0.47l0,0.5l0.58,-0.17l0.18,-1.51L277.4,69.77zM252.98,69.62l0.31,0.15l0.6,-0.32l0.62,1.02l0.89,0.16l1.53,2.56l1.47,-0.2l2.47,-0.89l1.64,0.71l0.56,1.04l2.31,1.28l0.5,1.83l0.79,0.73l0.42,1.15l1.62,1.15l1.35,0.31l2,1.04l0.69,1.3l0.88,0.82l0.06,0.75l-1.65,2.51l-2.88,1.38l-0.52,-0.05l-0.69,-0.65l-0.49,-1.92l-1.49,-0.91l-0.05,-0.81l-0.42,-0.7l-2.09,-0.59l-1.21,-0.72l-0.49,-0.07l-0.61,0.39l-1.21,-0.9l-0.92,-1.16l0.66,-0.82l-0.28,-0.38l-1.29,-0.17l-1.36,-1.32l-0.5,-1.75l-0.65,-0.06l-0.27,0.81l-1.49,-0.1l-1.43,-1.09l0.48,-0.61l-0.5,-0.81l-0.43,-0.17l-1.12,0.55l-0.88,-0.6l-0.22,-1.6l1.55,-1.56l-0.28,-0.29l-0.05,-0.99l0.41,-0.66l0.8,0.01L252.98,69.62zM263.92,69.3l2.32,-0.04l0.66,0.43l1.06,1.49l1.95,-0.14l0.63,0.62L272,71.9l0.31,0.21l-0.16,0.8l1.01,0.87l0.86,1.6l0.65,0.11l0.61,0.92l0.98,-0.15l1.08,0.95l0.1,0.52l-1.76,1.25l-0.46,0.68l-0.48,0.11l0.12,0.87l-0.89,0.93l-2.31,-0.71l-1.43,-1.2l-0.08,-2.01l-0.79,-0.92l-1.23,-0.67l-0.76,-1.15l0.04,-1.07l-0.95,-1.49l-1.97,-0.89l-2.59,-1.97l-0.47,-0.71l0.53,-0.69l0.66,0.88L263.92,69.3zM297.59,67.97l2.31,0.21l1.27,0.7l-0.04,0.4l-0.8,0.58l0.44,1.75l-0.39,1.43l-2.34,3.74l-0.76,0.76l-2.31,0.71l-2.58,-0.7l-0.79,-0.72l-0.25,-0.85l-1.36,-0.69l-0.58,-0.89l1.52,-1.03l0.55,-1.11l0.86,-0.87l1.28,-0.44l0.86,-1.06L297.59,67.97zM223.04,64.49l0.36,0.67l1.28,0.72l0.28,1.66l-0.8,1.2l-0.89,0.3l-0.18,0.58l0.38,0.78l-1.13,0l-0.97,0.53l-0.5,1.16l-0.48,-0.81l0.7,-1.11l0.07,-0.71l-0.39,-0.54l0.12,-1.19l-0.57,-0.83l-0.04,-0.61l1.13,-0.55l0.06,-0.33l-0.41,-0.16l0.23,-0.32L223.04,64.49zM322.19,64.37l1.55,0.28l0.74,0.66l0.79,-0.05l1.47,1.91l0.65,1.5l0.18,0.61l-0.29,0.1l0.85,3.17l-1.62,1.69l0.76,0.19l0.2,1.55l0.46,0.65l-0.35,2l-2.82,4.97l-1.2,0.66l-2.51,2.21l-1.04,0.31l-0.95,-0.16l-2.82,1.21L316,87.75l0.05,-0.6l-3.98,2.3l-0.91,-0.12l0.01,-0.97l-1.89,-3.32l-1.7,-1.61l-0.1,-1.11l2.07,-2.79l2,-1.89l0.72,-1.54l1.04,-0.74l0.81,-0.29l3.71,0.17l1.02,-0.58l0.56,-1.8l-0.47,-2.75l0.63,-2.57l-0.15,-0.64l1.18,-1.54L322.19,64.37zM274.42,62.8l0.96,0.64l0.33,1.09l-0.77,-0.08l-0.55,0.81l-0.6,2.48l-0.46,0.62l-0.55,-0.13l-0.19,0.36l-1.1,0.11l-1.39,-0.18l-1.81,-1.54l-0.95,-0.44l0.53,-0.98l1.69,-0.69l0.9,-1L274.42,62.8zM293.41,60.29l0.29,0.82l-1.37,1.02l-1.58,-1.17l-1.72,-0.45l-0.76,-0.9l1.38,-0.82l1.64,0.14l1.47,0.5L293.41,60.29zM265.39,54.03l1.06,0.52l0.36,0.79l1.14,-0.32l2.07,1.98l0.71,-0.3l0.73,2.11l0.93,-0.24l0.25,-0.92l0.48,0.92l1.57,1l-1.99,0.81l-0.84,-0.14l-1.19,0.71l-0.94,0.18l-3.2,2.89l-0.28,0.72l-1.82,1.2l-1.21,-0.25l0.47,-1.65l-1.02,-0.67l-2.43,1.3l-2.41,-0.67l-0.25,-0.51l0.43,-1l-0.07,-1.2l-0.23,-0.24l-0.7,0.21l-0.18,-0.41l0.73,-1.47l-0.54,-0.81l1.4,-1.01l0.21,0.3l-0.22,0.64l0.61,0.38l1.12,-0.06l1.45,1.2l0.5,-0.33l0.53,0.2l0.47,0.93l1.75,0.61l0.43,-0.15l-0.84,-1.67l-0.79,-0.7l0.6,-1.71l-0.91,-2.61L265.39,54.03zM282.33,53.35l0.63,0.14l0.8,-0.27l0.27,0.25l-0.58,0.29l-0.07,0.71l0.6,0.55l0.8,2.56l-0.05,0.49l-0.65,0.77l-2.04,0.71l-2.4,-1.05l-0.8,-1.44l0.35,-1.36l1.49,-1.73l0.88,-0.7L282.33,53.35zM272.66,46.55l1.25,0.51l-0.15,1.41l0.58,0.3l0.08,0.77l1.03,0.68l0.95,-0.15l1.23,0.52l1.38,1.9l0.23,0.88l-0.22,0.76l-1.8,1.35L276,55.77l-2.11,-0.3l-0.72,-0.76l-1.09,-0.36l-0.45,-1.15l-0.74,-0.66l-0.37,0.3l-0.71,-0.28l-0.58,0.27l-0.46,-0.49l-1.58,-0.1l-0.31,-0.26l-0.12,-1.67l0.78,-0.22l-0.06,-1.99l0.64,-0.51l1.72,0.53l0.71,-0.6l0.39,0.18l0.48,-0.96L272.66,46.55zM312.84,39.29l1.73,0.31l0.99,0.61l0.75,0.81l0.56,1.63l-0.64,1.92l-1.03,1.12l-1.02,0.54l-2.05,-0.47l-1.33,0.08l-1.55,-0.67l-0.8,-0.73l-0.3,-1.89l-1.96,-0.29l-0.99,-0.85l0.56,-1.1l0.97,-0.5l1.77,0.07l1.25,-0.54l-0.04,0.57l-0.47,0.17l-0.13,0.41L312.84,39.29zM282.91,31.9l1.34,0.53l0.66,1.14l-0.1,1.45l-0.42,0.6l0.29,1.25l-0.76,1.21l-2.69,0.46l-0.27,0.36l-0.82,-0.42l-1.39,0.18l-0.57,0.77l-0.52,0.04l-1.01,0.92l-0.51,0.02l-1.24,-1.3l-0.08,-1.65l0.71,-1.07l-1.09,-2.14l2.17,-1.14l1.54,0.23l3.01,-1.41L282.91,31.9z"
},
{
"id":"RU-AST",
"title":"Astrakhan'",
"d":"M193.18,716.91L192.52,718.78L195.68,719.95L196.93,721.36L196.86,722.41L197.66,722.69L196.29,723.53L197.33,725.27L197,725.5L197.42,726.08L198.87,726.98L199.09,725.5L201.1,726.25L203.71,726.06L204.65,726.96L206.07,729.55L207.7,729.75L208.6,733.2L210.55,736.55L209.89,737.32L209.08,737.41L208.73,737.37L208.05,736.5L207.51,736.47L207.01,736.9L206.78,737.69L207.24,737.82L207.34,738.2L207.92,738.19L209.25,739.58L211.59,740.68L212.16,741.44L211.75,741.9L211.96,742.34L210.9,743.53L211.1,743.89L210.62,744.57L210.44,744.39L210.07,744.8L209.42,744.81L209.58,746.02L208.5,743.7L208.16,743.73L208.85,745.16L208.75,745.84L209.25,746.29L209.14,746.71L208.74,746.68L207.42,745.26L207.61,746.08L206.79,746.22L206.88,746.94L206.14,746.68L205.05,748.56L203.79,748.04L203,748.3L202.26,749.01L201.12,747.44L200.49,747.63L200.28,748.23L201.14,749.24L200.92,749.5L200.46,749.04L200.89,750.15L200.43,750.23L200.43,750.23L199.76,749.63L200.28,748.7L198.85,748.45L197.57,748.94L195.41,748.89L196.34,747.6L198.06,743.94L197.83,743.52L195.83,743.96L195.52,743.74L195.48,742.66L195.17,742.22L194.35,742.16L193.34,741.57L194.68,740.29L196.08,740.2L196.15,739.09L196.56,738.44L197.77,737.91L198.05,737.01L197.04,735.57L196.26,735.49L195.75,734.44L195.19,734.23L192.82,729.85L193.65,728.79L194.57,728.37L194.83,727.93L193.72,727.6L191.74,729.78L189.16,727.7L187.22,725.27L187.32,723.53L186.65,723.3L185.99,723.56L184.2,722.13L184.2,722.13L183.3,721.2L182.38,720.91L181.99,720.27L183.16,718.4L184.62,718.67L184.56,718.23L183.73,718.03L183.73,717.65L186.04,717.41L188.05,716.08L189.47,714.33L190.83,714.39L191.73,714.87L193.16,715.86L193.35,716.48L193.35,716.48z"
},
{
"id":"RU-BA",
"title":"Bashkortostan",
"d":"M249.25,625.48L250.81,623.07L251.46,623.28L251.81,624.19L252.55,624.38L253.26,625.06L254.87,624.53L256.1,625.28L256.76,625.07L257.65,624.22L259.22,623.73L259.71,623.83L261.03,626.3L261.46,626.56L262.61,626.22L263.61,625.37L264.28,625.33L266.93,628.8L267.56,628.8L269.35,627.85L269.48,627.31L270.86,625.87L270.86,625.87L271.01,626.55L271.72,627.4L271.44,628.05L271.89,628.52L272.97,628.04L273.63,628.08L274.69,628.85L275.14,628.93L276,628.38L277.01,628.52L277.31,628.87L279.07,627.89L280.9,629.09L281.67,629.23L282.43,628.28L282.43,628.28L283,627.95L283.45,628.2L284.51,627.94L284.85,628.44L284.8,628.8L283.73,629.62L283.92,630.82L283.18,632.36L284.53,633.22L284.32,633.74L284.52,634.87L285.2,634.63L285.87,635.23L286.89,635.27L285.8,636.86L283.59,637.18L283.31,637.58L283.5,638.27L282.6,639.14L282.17,639.32L281.07,638.76L280.31,639.33L280.35,639.79L279.61,640.57L280.69,641.03L281.11,642.05L280.23,642.92L279.42,643.25L278.84,642.17L278.45,642.33L278.06,642L276.95,640.31L276.26,641L276.09,641.99L275.09,643.5L274.78,643.39L275.34,642.45L275.02,641.04L275.67,639.99L275.42,639.4L271.82,638.62L269.79,639.78L268.79,641.82L269.86,643.08L269.15,644.57L273.07,647.67L273.33,648.58L274.41,649.88L274.9,650.03L275.5,649.88L276.72,648.66L278.01,648.32L279.56,649.15L280.18,649.11L280.74,648.03L282.9,647.23L283.51,647.57L284.02,647.45L285.48,646L286.1,644.67L286.71,644.44L287.24,643.69L287.68,644.44L288.78,644.26L288.47,645.06L288.86,645.88L287.99,648.05L287.12,648.84L287.48,649.62L286.88,650.49L287.78,651.19L287.42,653.13L286.35,652.72L284.41,652.93L283.61,654.91L282.88,655.56L281.85,655.77L281.54,658.87L280.9,660L281.31,660.68L281.36,661.82L281.31,663.56L280.91,663.89L281.46,664.53L281.61,665.81L282.01,666.45L281.06,667.58L280.88,670.52L280.59,671.15L281.3,672.3L280.94,672.98L281.28,673.54L281.28,673.54L281.17,673.88L281.7,675.16L281.26,675.78L280.67,675.6L280.22,675.92L279.95,677.43L280.58,678.1L279.78,681.03L279.2,681.65L278.21,681.77L277.09,682.41L276.68,682.34L275.97,681.42L274.42,680.98L273.77,681.08L273.46,680.72L273.02,680.82L272.17,682.62L271,682.29L270.9,683.28L269.68,684.07L268.55,682.6L267.57,681.98L267.18,682.22L267.54,683.4L267.15,683.92L266.5,683.81L266.78,682.73L265.52,680.7L266.18,679.71L265.39,678.02L264.06,676.67L263.75,676.68L263.21,677.58L262.51,676.85L263.69,675.69L263.97,674.88L263.82,673.69L263.24,672.92L263.65,672.13L263.43,671.91L262.92,672.29L261.25,671.14L260.94,672.41L259.32,674.61L257.31,674.01L256.8,671.89L256.05,671.26L255.51,671.4L255.19,671.05L255.44,670.47L256.03,670.62L256.39,670.24L256.11,670.02L255.93,668.8L254.71,669.18L254.15,668.8L254.12,668.06L253.3,666.8L252.8,664.31L252.46,664.03L250.83,664.38L250,662.96L248.69,662.36L247.89,662.45L246.72,661.46L245.04,658.86L243.73,657.49L242.71,655.32L242,654.51L242,654.51L242.25,653.69L241.86,651.94L242.25,649.67L242.54,648.53L243.72,646.56L243.48,645.32L244.09,644.21L243.79,643.76L242.87,643.8L242.17,642.72L241.09,641.82L240.23,641.55L240.52,640.9L242.24,640.21L243.02,640.23L244.08,638.86L245.67,637.99L246.05,636.78L246.5,636.31L246.43,635.49L247.8,634.24L247.76,633.22L246.86,632.75L247.02,632.52L246.49,632.19L245.97,631.02L244.91,630.52L244.91,630.52L245.29,629.8L247.09,628.55L247.8,627.04L249.14,626.33z"
},
{
"id":"RU-BEL",
"title":"Belgorod",
"d":"M112.93,690.26L113.61,690.41L113.96,691.09L114.96,690.92L115.56,690.46L116.18,690.75L116.66,689.93L117.21,689.79L117.38,689.27L116.94,689.03L117.57,688.32L118.17,688.98L119.12,688.63L119.78,689.1L121.67,689.51L123.07,688.33L124.88,688.02L125.6,686.87L127.09,686.54L127.56,686.17L129.06,686.07L130.15,686.34L131.12,685.68L131.88,685.62L134.28,687.3L134.28,687.3L135.55,687.65L135.75,688.08L135.71,688.64L135.07,689.03L135.16,689.82L136.74,690.35L137.68,689.53L138.34,690.12L138.17,690.93L138.7,691.49L138.45,691.8L137.72,691.55L137.52,692.49L138.27,692.9L138.16,693.42L138.74,694.17L139.27,694.14L139.73,694.84L140.82,695.25L140.7,695.61L140.03,695.58L140.32,696.27L139.79,696.96L140.37,697.96L140.14,698.51L140.58,700.44L141.42,701.22L141.49,701.8L140.89,703.39L140.44,703.7L140.44,703.7L140.04,703.06L139.68,703.54L138.54,703.91L138.3,703.22L137,702.75L136.57,701.75L136.4,702.19L135.25,702.09L135.06,701.74L134.54,701.87L134.07,700.77L133.07,700.88L133,701.7L133.26,702.01L131.88,702.59L131.98,702.22L131.04,701.06L129.91,700.66L129.14,699.76L129.1,698.32L128.64,698.39L127.92,697.78L127.94,696.85L127.4,697.14L126.87,697.03L125.66,697.83L123.45,697.99L122.03,699.18L121.4,698.86L121.56,698.37L121.29,698.53L120.58,697.99L119.55,698.45L119.3,697.72L118.4,696.71L117.82,696.54L116.1,696.7L115.42,697.71L114.65,697.7L114.3,696.51L113.79,696.34L113.08,695.13L113.12,694.37L113.73,694.15L113.64,693.08L112.96,691.86L113.03,691.25L112.59,691.07L112.61,690.3z"
},
{
"id":"RU-BRY",
"title":"Bryansk",
"d":"M99.68,655.13L100.81,654.97L101.78,655.56L102.61,657.02L102.97,656.87L103.25,657.22L104.6,656.8L104.8,657.33L105.86,658.11L105.86,658.6L106.6,659.06L106.76,661.96L107.44,662.48L108.11,662.48L109.29,663.04L110.25,662.91L111.03,663.85L111.03,663.85L111.12,665.2L110.77,665.45L112.01,666.12L111.89,666.93L111.12,666.94L111.14,667.59L110.31,667.85L109.95,667.26L109.84,667.82L109.14,667.71L109.23,668.32L108.48,668.57L109.08,669.67L109.39,669.31L109.86,669.84L110.38,669.77L110.15,670.28L110.48,670.82L110.24,671.17L109.79,671.02L110.09,671.64L109.82,672.03L110.31,672.46L108.97,673.54L108.94,674.22L109.34,674.12L109.8,674.61L109.8,674.61L108.77,676.32L108.51,676.47L107.94,676.14L107.57,676.4L107.87,677.07L107.6,677.84L106.16,677.79L105.27,678.47L105.09,679.44L105.92,679.72L105.3,680.48L105.3,680.48L105.11,680.31L104.77,680.63L104.85,680.06L104.57,680.09L103.96,679.16L103.52,679.03L103.45,678.06L103.77,677.44L103.41,676.75L102.54,676.12L102.4,675.48L101.83,675.46L101.74,674.83L100.98,674.86L99.44,675.58L99.58,674.92L98.7,674.8L98.25,675.05L97.18,674.62L97.05,675.05L96.36,675.45L96.16,675.3L95.13,676.16L94.92,675.81L93.54,676.04L92.63,675.18L91.38,674.96L91.18,675.29L91.45,676.05L90.97,676.25L91.2,677.31L90.75,677.93L90.12,678.33L89.76,678.19L89.13,678.73L88.13,678.65L88.25,678.02L87.23,677.88L87.04,676.89L86.32,676.77L86.51,675.85L85.7,675.47L85.92,674.28L85.64,673.84L85.83,673.32L85.56,673.17L85.78,672.66L85.98,672.87L86.21,672.53L85.55,672.08L85.13,670.93L85.53,670.76L85.76,669.91L85.24,669.29L85.31,668.91L84.41,668.44L84.08,667.54L83.23,666.83L83.73,666.9L83.93,666.26L84.31,666.15L84.16,665.74L84.51,664.92L85.51,664.96L85.97,664.48L86.84,664.79L87.38,665.83L87.99,665.87L88.12,666.22L90.24,666.1L90.34,665.73L90.95,665.63L91.15,665.12L91.82,664.93L92.4,663.99L92.26,663.73L92.9,663.8L93.57,663.22L93.93,663.28L93.98,662.6L94.31,662.5L94.06,662.32L94.06,662.32L94.76,661.93L95.17,662.2L95.2,661.33L95.55,660.86L95.4,660.4L96.49,659.5L97.01,658.56L97.45,658.68L97.6,657.57L98,657.85L98.34,657.46L97.81,656.79L98.35,655.6L98.91,656.1L99.25,655.76L99.05,655.42z"
},
{
"id":"RU-BU",
"title":"Buryat",
"d":"M570.53,667.99L570.82,667.04L571.68,666.4L571.67,665.76L573.44,665.51L575.17,664.42L575.23,663.21L576.94,663.38L577.25,662.61L578.13,662.34L578.78,663.9L578.82,665.54L579.41,666.51L581.67,668.04L582.58,669.36L586.12,671.55L587.78,673.23L588.37,674.66L589.48,675.16L590.67,676.27L591.46,675.79L592.77,676.14L593.57,675.9L594.59,676.34L594.76,677.54L595.23,677.74L596.64,679.72L598.63,680.65L599.32,682.5L599.18,683.76L599.47,684.82L600.1,685.42L602.47,685.42L603.51,686.19L603.51,689.11L604.25,688.91L604.82,688.31L605.89,688.08L606.35,687.53L607.75,687.37L608.39,686.96L608.82,687.24L609.3,686.73L609.28,685.3L609.85,684.26L614.66,681.58L622.82,672.05L630.35,667.56L634.22,663.74L637.15,654.94L637.41,649.18L637.86,648.58L637.34,648.6L637.91,647.29L638.4,646.89L638.33,644.41L638.6,643.57L638.39,642.08L638.84,639.99L638.23,639.59L638.13,639.14L638.05,637.08L638.47,636.41L638.3,635.55L638.79,635.19L639.86,631.36L640.6,631.12L641.85,631.28L642.23,630.68L640.97,629.92L640.45,629.96L639.51,627.44L638.49,627.04L637.54,625.91L638.62,624.21L638.69,623.56L638.31,623.32L638.51,622.99L640.21,622.75L641.33,621.66L642.19,621.71L644.18,620.92L645.63,621.22L646.89,620.13L647.15,618.6L647.82,617.7L650.54,618.23L651.9,619.35L653.11,618.96L653.75,619.24L654.96,619.11L655.93,619.66L657.26,618.41L657.2,617.8L657.84,616.58L658.91,615.64L659.39,615.84L660.81,618.24L661.19,618.33L661.59,617.84L662.84,618.02L663.77,618.93L665.3,619.2L666.53,617.82L667.13,617.88L667.21,619.71L668.56,621.04L671.15,621.94L673.49,621.49L674.93,622.27L675.2,623.01L676.05,623.18L676.45,623.08L676.71,622.25L677.72,621.21L679.86,621.54L680.49,621.03L682.08,621.01L682.48,620.66L682.88,619.27L684.3,617.13L684.31,615.75L688.26,615.68L689.57,614.29L691.68,614.17L692.67,615.39L691.81,615.72L689.2,617.95L689.2,617.95L689.2,617.95L689.2,617.95L689.2,617.95L689.2,617.95L688.04,619.02L688.25,620.88L687.08,622.07L688.71,622.95L689.05,624.1L689.4,624.35L689.49,624.79L688.89,624.96L688.88,625.76L689.91,628.19L689.49,630.13L690.1,631.47L689.9,633.13L690.41,634.65L690.65,638.23L692.25,638.78L693.89,638.67L695.38,640.88L696.85,641.9L697.75,644.46L697.15,646.68L696.75,646.97L696.76,647.69L696.04,648.63L694.8,648.78L694.49,649.08L692.95,648.93L687.83,650.44L687.05,651.92L685.37,652.85L682.73,655.2L681.02,655.85L680.15,657.47L679.11,657.47L678.9,657.86L676.47,658.69L675.48,659.88L675.49,662.34L676.18,663.01L676.19,663.96L677.33,664.84L677.86,664.78L678,665.51L677.53,665.98L677.8,666.28L678.92,666.46L678.69,667.96L678.38,668.12L678.27,669.36L677.06,671.06L674.97,671.66L673.48,673.44L670.31,673.78L668.89,674.98L666.57,674.85L665.97,675.11L665.17,676.3L663.63,675.97L663.33,675.56L662.66,675.74L659.54,679.69L655.38,681.32L654.87,682.24L653.94,682.9L653.72,683.97L652.62,684.8L650.87,684.6L650.44,683.78L647.66,683.69L646.5,684.29L645.27,685.61L642.51,686.49L641.23,685.83L641.14,685.4L638.68,685.54L637.84,684.96L637.76,685.98L637.43,686.2L637.05,686.01L636.84,687.31L636.24,688.42L637.51,689.42L636.74,690.12L635.68,690.39L635.34,693.33L634.39,693.83L634.22,694.35L634.95,695.1L636.66,695.68L637.24,696.49L638.27,696.6L637.92,697.42L636.86,697.14L635.76,697.89L634.96,698.03L634.04,698.85L633.45,698.76L632.89,700.1L631.56,700.98L631.72,701.92L631.72,701.92L631.37,702.23L630.56,702.19L629.26,702L628.74,701.49L628.34,701.82L627.45,701.51L626.16,699.25L624.66,698.14L623.3,697.85L621.23,698.43L619.89,697.81L619.57,697.13L616.44,696.9L614.84,696.37L614.24,696.42L612.91,697.34L611.75,697.28L609.11,698.23L607.79,698.32L606.93,698.91L606.52,699.65L605.32,700.01L603.48,699.4L602.52,700.18L600.87,699.32L600.01,699.48L599.34,698.3L597.11,698.22L596.46,697.5L595.15,696.93L594.35,695.77L593.44,695.56L592.71,695.01L592.65,694.45L593.11,693.44L592.16,692.29L592.46,690.88L591.94,689.67L591.63,687.48L592.07,686.81L591.14,686L588.71,685.22L588.09,685.33L587.52,684.77L586.81,684.79L586.08,685.25L585.1,684.24L584.4,684.28L579.9,681.89L576.16,681.85L574.25,680.14L571.34,679.44L570.99,678.76L569.38,678.16L568.96,677.56L568.96,677.56L568.83,676.48L567.84,676.58L567.6,676.34L567.73,675.58L566.51,675.75L566.51,673.91L567.71,672.68L567.82,671.69L568.55,670.97L568.78,669.55L568.24,669.64L568.05,669.38L568.28,668.44L569.08,667.92L569.73,668.52L570.44,668.69z"
},
{
"id":"RU-CE",
"title":"Chechnya",
"d":"M185.91,764.96L187.46,765.69L188.3,765.36L189.63,765.7L189.6,766.91L190.13,766.4L191.05,766.26L190.95,765.67L192.04,764.76L192.62,765.54L192.61,765.99L193.33,766.37L193.43,766.79L193.27,767.63L191.63,770.47L192.42,772.5L192.28,773.84L192.81,774.11L192.7,774.93L192.97,775.32L192.21,776.09L191.9,776.05L191.69,775.58L190.78,775.88L190.04,776.49L190.67,777.36L189.35,777.73L189.13,778.67L188.58,778.59L188.31,779.25L187.37,779.79L187.37,779.79L185.91,778.96L184.2,779.11L183.02,777.51L182.46,777.53L182.46,777.53L182.97,776.89L182.88,776.26L183.32,775.63L183.03,774.53L183.99,772.72L184.05,771.54L183.25,771.16L183.39,770.27L181.31,769.3L181.31,769.3L181.54,768.24L181.54,768.24L181.87,768.38L182.69,767.84L182.85,765.95L183.7,765.74L183.98,766.56L185.03,766.59L185.56,766.22L185.52,765.29z"
},
{
"id":"RU-CHE",
"title":"Chelyabinsk",
"d":"M282.43,628.28L282.58,627.24L282.99,627.35L283.51,626.95L283.35,625.71L284.15,625.29L284.96,625.75L286.71,625.93L287.39,627.03L289.13,626.61L290.29,627.02L292.33,626.47L293.52,627.19L294.36,626.94L294.96,627.27L297.56,627L297.06,625.77L298.02,625.01L298.88,625.4L299.7,625.12L300.4,625.89L301.64,625.83L301.73,626.33L302.51,626.61L302.9,627.52L303.95,627.97L303.95,627.97L305.17,629.61L305.45,630.96L306.35,631.01L306.03,631.63L307.61,633.16L307.35,633.55L307.73,635.04L307.17,635.71L307.86,635.9L307.64,636.73L306.99,637.12L306.29,637.38L304.88,637.21L305.23,638.55L304.13,639L305.54,641.45L305.09,642.63L304.72,642.64L304.22,642.09L303.45,642.3L303.41,643.01L304.32,645.16L304.04,645.81L305.05,646.83L307.19,645.95L307.8,646.33L307.54,646.85L308.85,647.01L310.83,646.3L312.36,646.4L312.96,648.7L311.75,649.47L311.99,650.11L311.68,650.71L313.12,651.98L313.51,652.01L313.61,652.81L313.61,652.81L312.1,652.87L312.06,653.67L311.76,653.91L309.58,653.81L309.46,654.23L307.98,655.4L307.67,656.44L306.89,655.99L306.69,655.27L307.23,654.9L306.74,654.54L305.2,654.82L304.25,654.54L303.75,654.87L304.03,655.77L303.6,655.88L302.83,655.63L303.07,655.12L302.65,655.1L302.68,654.82L302.23,655.41L301.84,654.86L301.28,655.07L300.95,655.78L300.72,655.28L300.11,654.98L299.86,654.2L299.38,654.13L298.75,654.32L298.39,654.8L298.39,656.22L297.9,656.15L297.68,655.69L296.75,655.8L296.48,656.47L297.53,656.67L298.12,657.69L296.89,658.88L296.85,659.57L296.55,659.23L295.97,659.26L295.95,659.86L299.1,660.56L300.16,660.17L300.77,660.97L299.74,661.77L299.26,661.35L298.4,661.23L298.24,662.02L297.69,662.63L297.86,663.71L299.39,664.06L300.27,664.7L301.01,664.67L301.34,664.24L302.28,665.33L304.52,665.86L304.71,667.18L303.78,667.82L302.84,667.11L301.68,667.28L301.15,667.69L299.85,666.83L299.22,667.4L298.25,666.87L297.39,667.6L296.73,667.48L297.08,668.29L295.51,669.94L294.61,670.19L294.51,671.34L295.42,671.76L295.47,672.95L296.37,673.11L297.07,675.06L296.3,675.81L295.08,676.3L294.56,677.03L293.19,677.07L291.33,678.86L290.22,679.03L290.22,679.03L289.27,678.37L290.04,676.66L291.06,675.77L290.69,674L289.17,674.17L288.21,673.51L287.95,673.73L287.1,673.31L286.22,673.59L285.99,673.12L285.67,673.17L284.27,673.76L284.04,674.39L284.29,675.48L282.89,674.65L282.31,673.52L281.28,673.54L281.28,673.54L280.94,672.98L281.3,672.3L280.59,671.15L280.88,670.52L281.06,667.58L282.01,666.45L281.61,665.81L281.46,664.53L280.91,663.89L281.31,663.56L281.36,661.82L281.31,660.68L280.9,660L281.54,658.87L281.85,655.77L282.88,655.56L283.61,654.91L284.41,652.93L286.35,652.72L287.42,653.13L287.78,651.19L286.88,650.49L287.48,649.62L287.12,648.84L287.99,648.05L288.86,645.88L288.47,645.06L288.78,644.26L287.68,644.44L287.24,643.69L286.71,644.44L286.1,644.67L285.48,646L284.02,647.45L283.51,647.57L282.9,647.23L280.74,648.03L280.18,649.11L279.56,649.15L278.01,648.32L276.72,648.66L275.5,649.88L274.9,650.03L274.41,649.88L273.33,648.58L273.07,647.67L269.15,644.57L269.86,643.08L268.79,641.82L269.79,639.78L271.82,638.62L275.42,639.4L275.67,639.99L275.02,641.04L275.34,642.45L274.78,643.39L275.09,643.5L276.09,641.99L276.26,641L276.95,640.31L278.06,642L278.45,642.33L278.84,642.17L279.42,643.25L280.23,642.92L281.11,642.05L280.69,641.03L279.61,640.57L280.35,639.79L280.31,639.33L281.07,638.76L282.17,639.32L282.6,639.14L283.5,638.27L283.31,637.58L283.59,637.18L285.8,636.86L286.89,635.27L285.87,635.23L285.2,634.63L284.52,634.87L284.32,633.74L284.53,633.22L283.18,632.36L283.92,630.82L283.73,629.62L284.8,628.8L284.85,628.44L284.51,627.94L283.45,628.2L283,627.95z"
},
{
"id":"RU-CHU",
"title":"Chukot",
"d":"M1062.96,408.94l-0.76,-0.54l1,-2.08l1.5,-0.95l-0.1,-0.38l0.52,-0.1l0.57,-0.71l0.65,-0.12l-0.05,0.27l1.2,0.04l-0.05,0.4l0.81,0.12l-0.13,0.46l0.62,-0.14l-0.1,0.2l0.55,0.18l-0.13,0.25l0.44,-0.53l0.33,0.72l2.74,0.54l1.45,0.87l0.24,0.96l-0.28,1.07l-0.94,-0.12l-0.13,0.34l0.41,0.5l-0.38,0.22l0.27,1.12l-0.38,1.53l-0.51,0.67l-0.87,-0.22l-1.06,0.17l-3.86,-1.57l-1.73,-1.28l-0.18,-0.69l0.27,-0.16L1062.96,408.94zM1202.99,504.53l0.65,-0.23l0.44,0.55l-0.36,0.4l-1.28,-0.13l-0.44,-0.36l0.32,-0.58L1202.99,504.53zM1140.04,383.41l-0.2,-1.92l1.87,-2.22l0.09,-1.06l2.02,-1.29l2.18,-3.11l1.52,-1.12l-0.09,0.36l0.48,0.09l0.3,-0.64l0.5,-0.1l0.46,-1.06l0.51,-0.27l0.05,0.28l1.47,-0.04l-0.54,-0.36l0.17,-0.34l0.52,0.14l0.4,-0.62l0.07,0.59l0.24,0.03l0.5,-0.8l0.14,0.48l0.55,0.03l0.02,0.46l0.46,-0.29l0.95,0.44l0.4,-0.33l0.31,0.19l0.96,-1.12l3.17,0.46l-0.01,0.29l0.77,-0.01l2.04,0.98l-0.62,0.11l0.76,0.49l-0.11,0.5l0.73,-0.06l0.04,-0.41l0.26,0.15l0.75,0.8l-0.49,0.29l0.4,0.43l-0.54,-0.02l1.05,0.31l0.69,1.2l1.65,1.7l0.65,-0.18l0.03,0.54l0.53,0.65l-0.21,1.47l-0.49,0.3l-0.27,0.79l-2.38,1.81l-1.69,0.27l-1.83,0.88l-2.6,0.39l-3.29,1.54l-2.32,0.54l0.64,-0.46l-0.73,-0.77l-0.9,-0.69l-2.15,-0.57l-0.88,0.29l-1.5,1.68l-1.17,0.69l-0.63,0.08l-0.4,-0.31l0.84,0.16l0.21,-0.18l-0.31,-0.35l-0.43,0.24l-1.21,-0.11l-3.48,2.03l0.21,-0.29l-0.24,-1.8L1140.04,383.41zM1223.8,478.69l0.2,1l-0.47,1.29l-0.63,-0.04l-0.69,-0.66l-0.82,0.16l-0.91,0.44l-2.75,2.83l0.38,0.82l-0.36,0.6l0.17,2.05l-0.55,0.89l-1.91,-0.27l-0.13,-0.51l-2.12,-0.9l-0.72,-1.42l-1.11,-0.96l-0.41,-0.02l0.45,0.38l0.27,0.99l0.86,0.7l-0.38,-0.07l-0.03,0.45l0.59,0.75l1.22,0.48l0.57,0.76l-0.05,1.49l-0.47,0.56l-1.6,-1.1l-4.55,1.04l-0.22,-0.08l1.45,-0.58l-1.43,-0.13l-0.89,-0.71l-0.6,0.37l-0.29,-0.29l-0.45,0.07l0.24,-0.65l-0.63,-0.69l0.04,-0.4l-0.77,-0.63l-1.25,0.22l0.08,-0.4l-1.24,0.45l0.84,0.11l0.04,0.87l0.82,-0.03l1.09,0.63l-0.24,0.69l0.61,1.12l-0.96,0.16l0.62,0.75l1.23,-0.29l0.69,-0.81l-0.96,2.93l0.29,0.47l-0.18,1.39l0.89,1.98l-1.35,2.1l-0.89,0.78l-0.93,-0.11l0.08,0.3l-1.77,1.14l-1.35,-0.56l-0.97,0.6l0.16,0.49l-0.9,0.43l0.04,0.39l0.92,-0.38l0.99,-1.09l1.19,1.29l-0.24,0.59l-0.42,0.07l-0.06,0.57l-0.89,0.13l-0.66,0.48l0.04,0.23l0.76,-0.21l0.23,-0.36l0.58,0.3l-1.03,1.55l0.67,-0.04l0.31,-0.69l0.41,-0.07l0.5,0.12l0.09,0.41l0.59,0.01l0.34,0.49l1.11,0.15l0.39,1.13l0.97,1.2l-1.5,0.01l-1.11,0.5l-0.94,-0.47l-0.3,-1.8l-1.36,0.33l-0.52,0.55l0.08,0.26l1.13,-0.37l0.49,0.61l-0.36,2.12l-0.76,0.66l-1.23,0.27l-1.8,-0.86l0.07,-1.23l0.69,-0.6l0.11,0.31l0.62,-0.87l-0.67,0.26l0.3,-1.67l-0.38,0.08l-0.1,-0.98l-0.31,0.01l-0.17,-0.44l0.46,1.98l-0.15,0.79l-1.64,1.74l-0.7,0.09l-2.53,-1.57l-0.41,-1.94l-1.69,-1.51l0.44,-0.15l-0.12,-0.33l-0.95,0.28l-2.96,-2.19l-1.08,-0.45l-0.88,0.44l-1.95,-0.22l-0.23,-0.26l-0.46,0.25l-0.12,-0.42l0.5,-0.64l-0.73,0.04l-0.05,-0.68l-2.04,-1.01l0.01,-0.41l-0.87,-0.48l0.75,-0.64l0.36,-1.75l-0.96,-1.68l-0.32,-2.88l-0.58,-0.43l-7,-2.88l-1.01,0.14l-1.52,1.84l-1.03,0.43l-2.15,0.28l-0.42,-0.28l-0.88,0.18l-1.29,-0.26l-1.02,0.3l-1.9,-0.85l0.84,-3.79l-0.38,-0.59l-0.89,0.29l-0.74,-1.15l-0.08,-0.74l-1.19,-1.09l0.4,-0.46l-0.16,-1.03l0.64,0.15l0.65,-0.78l-0.11,-0.99l1.32,-0.76l-0.2,-0.83l0.45,-0.85l-0.41,-0.41l0.49,-0.68l-0.15,-1.75l-0.28,-0.27l-0.26,0.86l-0.39,-0.09l-0.96,2.88l-0.85,0.61l-0.57,0.07l-0.7,-0.53l0.05,-0.45l-0.43,-0.59l0.29,-0.47l-0.09,-1.81l-0.41,0.35l-0.07,1.34l-0.26,0.15l-1.63,-0.76l0.02,0.55l1.26,1.49l-0.23,0.62l-1.1,0.82l-1.03,-0.19l-0.48,-0.8l-0.63,0.06l0.15,0.29l-0.68,1.08l-0.19,3.28l1.09,2.73l2.5,1.96l-0.41,1.04l0.49,0.64l-1.53,2.14l0.12,0.65l-0.36,0.71l-0.16,1.63l-0.99,1.73l-0.74,0.1l-0.9,1.04l-1.82,1.27l-2.27,3.19l-2.87,0.81l-4.1,3.24l-0.33,-0.39l0.8,0.01l1.31,-0.99l-0.33,-0.49l-2.75,0.61l-1.65,-0.59l-0.88,0.43l-0.13,-0.61l-2.08,-0.16l-0.62,-1.06l-0.67,-0.15l0.06,-0.58l-0.59,0.12l-0.38,-0.4l0.88,-0.5l-0.31,-0.2l0.08,-0.77l-0.28,-0.27l-1.32,0.11l-0.09,1.07l0.58,0.69l-1.91,0.91l-0.25,-0.49l-0.47,-0.02l-0.14,-0.72l-0.36,-0.21l-0.44,0.24l-0.59,-0.41l-0.66,-0.07l-0.82,0.92l-0.68,0.04l-0.12,-0.83l-1.37,-0.6l-0.99,-0.78l-0.02,-0.33l-0.42,0.02l-0.73,0.97l-0.37,1.21l-0.95,0.85l-0.55,0.3l-0.67,-0.53l-1.55,0.71l-0.92,-0.19l-0.4,0.36l1.23,0.44l1.13,-0.72l1.38,0.26l1.54,-1.1l0.5,-0.75l0.08,-0.94l0.97,-0.01l0.47,0.33l0.74,1.87l0.92,1.09l-0.09,0.58l-1.66,0.81l-0.17,0.46l0.19,0.11l0.3,-0.42l0.77,0.18l0.58,-0.37l0.31,-0.76l0.54,0l1.09,0.72l0.4,1.38l2.23,-2.81l1,0.07l1.02,-0.83l1.13,0.17l-0.16,1.98l-0.54,1.07l0.05,1.21l0.53,1.27l2.6,2.85l1.38,0.66l0.86,-0.08l-0.4,-0.5l1.53,-1.76l-0.75,-1.71l3.06,6.86l1.01,5.48l0.12,2.4l0.55,1.89l1.48,2.5l1.65,1.13l0.88,1.32l0.1,0.82l-1.04,0.15l-0.36,1.15l0.48,1.51l1.3,0.27l0.3,0.33l0.49,2.46l-0.23,0.95l-0.96,0.55l-0.09,0.94l-0.6,0.87l-1.08,-0.23l-0.54,0.51l-0.19,0.56l0.52,0.49l-0.27,0.5l0.21,0.58l-0.56,0.66l-0.51,-0.94l-5.04,-1.84l-1.75,-1.11l-3.71,-0.5l-3.15,0.33l-1.35,0.42l-2.51,1.3l-2.48,2.24l-1.73,0.43l-3.06,1.46l-2.41,2.12l-2.92,1.5l-0.64,0.87l-1.6,0.71l-0.53,-0.21l0,0l0.09,-0.72l-0.51,-0.45l-0.17,-0.95l-0.58,-0.48l-0.3,-1.28l-0.85,0.21l-0.49,-0.36l-0.15,-1.85l-0.75,-0.44l1.2,-1.4l-0.36,-1.17l-0.63,-0.49l-0.91,-0.07l-0.34,-0.67l-0.78,-0.25l-4.25,1.44l-2.23,1.48l-0.84,-0.73l-1.34,-0.52l-0.96,0.21l-0.43,0.43l-1.17,0.05l-0.35,-0.65l-0.86,-0.36l-1.36,0.74l-0.5,0.89l-3.22,1.14l0.15,-0.72l-0.25,-0.07l-0.77,0.56l0.1,-0.95l-0.24,-0.17l-0.42,0.21l-0.24,0.69l-0.68,0.09l-0.03,0.6l-1.24,0.19l-0.21,0.53l-3.42,-1.23l-0.95,0.83l-0.43,-0.37l-0.28,-1.53l-0.56,-0.65l0.18,-0.63l-0.73,-0.76l0.21,-1.14l-0.29,-0.84l-0.77,-0.06l-0.62,-0.6l-0.66,0.03l-0.85,-1.49l-3.36,-2.48l-1.12,0.27l-1.26,-0.52l-0.48,-0.74l-1.87,-1.08l0.08,-0.7l0.69,-0.27l0.25,-0.53l0.9,-0.19l0.88,-1l-0.01,-1.12l0.58,-0.4l0.32,-0.89l0.97,-0.37l1.23,-1.64l1.23,-0.31l0.76,-0.64l-0.08,-0.4l0.48,-0.68l-0.81,-3.08l-1.03,-0.63l0.07,-0.94l-0.68,-0.35l-1.74,-0.17l-1.03,-1.23l-0.55,-2.82l-1.41,-0.32l-0.48,-0.68l-0.26,-1.35l-1.37,0.33l-0.39,-0.27l-0.7,0.65l-1.12,0.29l-0.66,-0.22l-0.13,-0.84l-1.01,0.34l-0.48,-0.21l-0.1,-1.61l-1.14,-0.58l-0.74,-0.81l-1.1,-1.99l-0.49,0.16l-0.74,1.08l-1.16,0.48l-0.89,-0.16l-1.18,0.37l-1.18,-1.33l-2.09,-0.58l-0.74,1.06l-0.79,0.17l-0.51,-0.31l0.27,-0.98l-0.85,-2.08l-2.64,-0.15l-0.58,-1.26l-0.66,-0.25l-1.15,0.39l-0.32,0.59l0.34,1.42l-0.58,0.44l-1.2,-2l-0.86,-0.01l-2.85,-2.1l-0.94,-0.01l-0.66,0.58l-1.23,0.05l-0.58,-0.54l-0.86,-0.08l-0.44,-0.38l-1.56,2.14l-0.77,-0.14l-0.36,0.27l-0.04,0.59l0.54,0.55l0.04,0.67l0,0l-3.18,0.13l-1.5,-1.57l-3.39,-0.58l-1.44,-1.01l-1.59,-3.27l-1.09,-0.19l-1.63,-1.18l-4.78,-0.87l-2.97,-3.52l-0.67,-2.05l-2.01,-0.43l-0.59,-0.92l-4.58,-1.67l-1.16,-1.32l0.07,-4.2l0.49,-1.27l1.33,-1.83l0.08,-0.65l-1.96,-0.11l-1.61,-1.03l-0.26,-0.83l-0.96,-0.08l0,0l0,0l0,0l-0.57,-0.76l-0.29,-1.18l0.85,-0.6l0.27,-1.17l1.26,-1.86l-0.07,-0.88l0.47,-0.96l1.09,-0.62l-0.15,-0.63l-1.14,-1.45l0.3,-1.69l-0.25,-1.13l-2.18,-1.09l-1.25,-0.2l-1.38,-1.87l-1.33,-0.42l-0.21,-0.53l0.2,-2.15l-0.84,-1.53l-0.15,-1.71l0.37,-2.55l1.15,-0.28l0.9,0.16l0.99,-0.43l0.39,-0.67l-0.07,-0.37l-0.91,-0.48l-0.4,-0.98l1.07,-1.39l0.63,-2.5l1.31,-0.96l2.65,0.16l2.78,-2.4l0.61,0.69l0.72,0.03l0.41,-0.3l1.11,0.51l0.48,-1.16l0.55,-0.59l0.74,-0.19l5.34,0.55l1.54,-0.62l2.26,-2.06l1.02,-0.23l4.42,1.35l2.7,1.26l0.58,-0.98l-0.05,-1.63l0.42,-0.77l-0.09,-1.88l0.88,-0.54l-0.11,-0.84l0.35,-0.92l-0.81,-0.63l-0.09,-1.12l0.89,-0.58l0.7,-1.24l-0.73,-1.57l-1.23,-0.48l-0.43,-0.81l0.48,-2.99l1.44,-0.33l-0.04,-0.59l-2.13,-2.73l-0.09,-1.54l-0.92,-0.46l0.27,-1.03l-0.75,-1.11l0.71,-0.35l0.53,-1.53l-0.09,-0.84l0,0l0.11,-0.87l1,0.72l-0.08,-0.28l0.44,-0.27l1.27,0.64l0.8,0l3.24,-1.44l1.31,0.65l1.3,0.11l1.5,-0.41l1.26,-1.33l0.66,0.16l0.91,1.68l2.36,1.79l2.18,0.42l2.14,-0.62l1.62,0.37l2.26,-0.01l3.56,1.34l2.19,0.19l0.98,-0.37l0.59,0.61l1.45,0.1l1.71,-1.47l3.3,-3.97l1.03,-0.51l1.03,1.15l0.92,0.22l0.13,0.37l-0.36,-0.08l-0.34,0.34l-0.19,0.81l1.13,1.11l1.07,0.56l-0.38,4.36l0.41,2.1l0.51,0.42l2.74,0.17l1.22,0.69l1.7,1.55l0.88,0.24l0.53,-0.18l0.73,1.31l0.27,1.86l-0.31,1.15l0.36,1.14l1.05,1.01l0.76,0.05l4.45,-0.97l1,-1.2l2.6,-1.71l1.44,-1.96l0.02,-1.12l-0.31,-0.69l-0.92,-0.6l0.31,-2.37l-0.58,-1.54l-0.46,-0.14l-0.04,-1.77l-0.45,-0.4l0.1,-0.74l-0.42,-1.08l-0.75,-0.59l-1.81,0.43l-0.87,-0.27l0.23,-1.51l0.64,-0.63l-0.17,-0.13l1.63,-0.48l0.78,-0.77l-0.58,-3.08l0.46,-3.46l-0.22,-0.37l-0.78,-0.25l0.09,-0.43l0.67,-0.12l1.65,0.94l1.54,-0.12l1.9,0.67l1.29,0.11l2.9,1.26l2.87,0.48l1.73,0.73l1.75,-0.67l0.49,0.65l0.05,0.66l2.24,1.41l0.47,-0.05l-0.03,-0.88l0.43,-0.59l1.69,-0.58l1.6,1.45l-0.27,0.32l0.72,0.94l1.3,-1.01l1.24,-0.39l0.2,0.21l0.63,-0.21l0.11,0.48l0.34,-0.03l0.08,-0.44l1.11,0.51l4.29,0.19l4.77,-0.88l1.3,0.31l1.27,-0.25l2.21,2.93l3.37,2.03l1.84,0.71l2.35,0.37l2.76,1.98l1.71,0.78l1.17,0.07l0.03,0.47l0.99,-0.53l2.99,1.28l4.29,3.31l4.16,4.89l1.57,1.33l1.26,0.36l0.65,-0.27l0.05,-0.42l0.56,0.28l-0.1,0.21l1.03,1.07l3.36,2.12l2.8,3.53l3.38,2.59l2.55,2.47l11.22,8.4l1.35,0.56l0.3,-0.19l-0.06,0.84l3.91,2.63l0.18,0.28l-0.43,0.35l0.45,1.48l1.26,1.63l0.7,0.36l1.29,1.44l0.54,2.32l-0.49,-1.15l-0.54,0.68l-0.3,3.45l0.39,1.77l0.53,0.96l0.62,0.37l-0.49,0.11l0.37,3.03l-0.43,-0.16l-1.32,1.61l0.72,1.01l1.27,0.19l1.79,1.19l0.16,1.04l-0.28,0.18l-0.14,1.3l0.74,0.93l1.46,-1.18l0.03,-0.93l0.92,-0.28l0.74,0.47l-0.27,0.46l0.27,1.78l-0.56,-0.02l-0.08,0.28l0.72,0.33l0.55,-0.1l0.3,-0.27l-0.63,-0.4l1.24,-0.49l0.2,-1.46l-0.83,-0.58l-0.35,-0.76l-1.53,-0.33l-1.17,-0.78l2.18,-1.66l-0.2,-3.15l-0.6,-2.39l-0.72,-0.3l-0.39,0.25l-0.23,-1.52l-2.05,0.5l-0.88,-0.24l0.02,-0.31l1.01,-0.35l5.46,-0.01l0.58,-0.7l1.47,0.69l2.64,0.71l0.38,-0.13l6.79,1.98l0.99,-0.77l0.8,0.53l0.69,-0.08l0.64,0.7l-0.46,0.65l0.32,0.63l2.24,1.63l-0.22,1.32l1.68,1.86l2.9,2.43l1.14,1.71l2.54,1.17l1.25,1.62l-0.5,-0.18l0.06,0.46l1.8,0.49l0.74,-0.2L1223.8,478.69zM1205.29,501.32l1.49,1.16l-3.78,1.3l-0.35,-0.41l0.98,-1.85l0.74,-0.42L1205.29,501.32z"
},
{
"id":"RU-CU",
"title":"Chuvash",
"d":"M190.09,629.99L192.81,628.19L193.67,628.64L194.17,628.55L194.88,627.68L197.5,625.91L198.7,625.79L199.13,626.16L199.74,627.78L200.55,628.25L202.71,628.61L203.56,630.82L206.45,632.36L206.45,632.36L206.48,633.09L205.46,633.3L204.93,634.16L203.73,634.61L203.77,635.28L204.56,635.69L203.48,636.56L202.29,638.32L201.51,638.55L201.37,638.93L201.26,639.96L201.71,640.12L202.23,639.48L202.66,639.53L202.6,638.81L203.15,638.99L203.93,640.98L202.98,641.51L202.84,642.21L203.26,642.77L204.2,642.38L204.19,642.76L201.94,643.15L202.3,644.44L201.3,644.39L201.42,645.09L200.27,644.94L199.28,644.18L199.37,644.6L198.89,645.01L199.42,645.82L198.17,646.34L198.17,646.34L197.37,647.02L196.77,646.51L196.11,646.58L195.25,647.45L194.73,646.85L193.95,646.89L192.44,645.83L192.44,645.83L191.99,644.26L190.98,643.4L191.44,642.66L191.18,642.05L190.79,641.87L190.26,643.04L190,643.06L189.81,642.24L189.81,642.24L189.4,640.64L189.83,639.95L190.76,639.39L191.05,638.26L192.02,637.6L191.83,636.84L190.29,636.18L188.84,634.8L188.83,633.97L189.85,632.6L189.67,630.88z"
},
{
"id":"RU-DA",
"title":"Dagestan",
"d":"M186.91,754.8L187.77,754.53L191.76,755.19L192.96,756.2L194.37,756.79L195.43,756.36L195.43,756.36L195.09,757.79L194.69,757.79L194.72,758.38L194.98,758.46L194.65,758.91L195.13,759.17L194.4,759.51L194.55,759.86L195.21,759.78L196.29,760.51L196.87,762.43L197.14,762.64L197.55,762.31L197.8,762.6L198.16,763.75L199.93,766.34L199.42,768.62L198.95,769L199.33,769L199.18,769.37L199.44,769.68L200.67,765.79L201.33,765.53L201.6,765.79L199.57,770.76L199.84,771.4L200.13,770.91L200.49,771.5L199.83,772.19L199.4,774.17L201.1,775.53L201.41,777.92L203.86,780.98L206,785.11L206.96,785.56L206.31,787.83L205.14,788.83L203.66,789.15L202.47,791.71L201.57,792L200.64,791.53L200.01,791.83L199.64,791.26L198.1,790.77L197,788.25L196.24,788.5L196.16,787.8L195.47,786.84L195.06,786.83L194.6,786.31L194.41,785.6L193.02,786.1L192.82,785.41L192.09,785.26L191.74,784.64L191.21,784.85L190.73,784.23L190.18,784.36L189.87,784.07L189.74,784.33L189.43,783.86L188.57,784L188.17,783.27L187.45,783.1L186.22,782.22L186.42,781.46L187.17,781.31L187.03,780.66L187.37,779.79L187.37,779.79L188.31,779.25L188.58,778.59L189.13,778.67L189.35,777.73L190.67,777.36L190.04,776.49L190.78,775.88L191.69,775.58L191.9,776.05L192.21,776.09L192.97,775.32L192.7,774.93L192.81,774.11L192.28,773.84L192.42,772.5L191.63,770.47L193.27,767.63L193.43,766.79L193.33,766.37L192.61,765.99L192.62,765.54L192.04,764.76L190.95,765.67L191.05,766.26L190.13,766.4L189.6,766.91L189.63,765.7L188.3,765.36L187.46,765.69L185.91,764.96L185.91,764.96L185.88,763.4L185.32,763.19L184.39,763.58L183.25,763.04L183.45,762.64L184.99,762.18L185.29,761.69L185.21,760.69L183.96,760.41L184.2,760.1L184.04,759.47L185.44,758.74L186.12,757.71L186.45,756.96L186.06,755.87z"
},
{
"id":"RU-AL",
"title":"Gorno-Altay",
"d":"M483.82,672.01L484.16,672.34L485.11,672.12L485.4,672.61L485.28,673.06L487.54,673.98L488.02,673.93L489.11,672.65L489.57,672.61L491.35,674.2L492.19,673.9L493.02,674.13L493.35,675.05L493.19,676.86L493.19,676.86L492.13,678.19L490.54,678.58L489.56,681.21L490.23,681.89L490.86,681.67L490.97,682.22L490.19,683.54L489.48,683.77L489.46,684.36L489.7,684.87L490.65,685.14L491.39,686L492.55,686.45L492.53,686.75L493.07,687.15L494.43,686.65L494.97,685.85L495.11,684.68L495.48,684.21L495.81,684.3L495.81,684.3L497.28,686.01L496.87,687.22L497.65,688.88L497.59,689.83L498.68,690.7L498.77,691.43L499.42,692.06L499.95,692.02L500.39,692.91L501.21,693.62L501.34,694.48L503.37,696.11L503.54,696.59L503.04,697.55L502.42,697.82L501.57,697.56L501.21,696.69L500.81,696.59L501.11,697.73L500.21,698.26L499.67,699.09L499.71,699.51L500.84,699.74L501.51,700.67L501.67,702.32L501.67,702.32L501.92,703.74L502.62,704.01L502.22,704.95L500.52,705.51L500.03,706.22L499.05,705.57L498.69,706.18L498.91,706.75L497.27,707.51L496.83,706.64L496.55,706.65L496.23,707.08L496.35,707.81L495.03,707.54L494.69,706.96L494.11,707.46L492.59,707.17L491.76,707.37L490.85,708.64L491.57,709.46L491.23,709.96L490.55,709.83L490.05,710.78L488.02,710.89L487.07,711.35L486.66,711.19L486.6,711.59L485.58,711.8L485.23,711.65L484.91,710.37L484.22,709.99L483.25,709.93L482.99,709.48L482.57,709.42L482.33,708.21L481.65,707.82L481.57,706.78L480.36,706.36L480.27,705.7L481.43,704.93L481.58,703.91L480.22,703.91L480.18,704.44L478.88,705.73L477.53,706.35L477.03,707.69L476.57,707.08L475.35,707.29L475.24,706.66L473.48,706.64L472.6,706.12L471.66,706.56L470.64,706.27L470.07,705.69L470.12,704.86L469.4,703.12L468.51,702.61L468.56,701.78L468.89,701.7L468.75,701.24L464.9,698.94L463.8,699.22L463.16,698.35L463.15,695.96L461.84,694.47L461.84,694.47L464.25,693.66L464.61,693.82L465.13,693.47L465.05,692.94L465.81,692.34L464.87,691.78L465.06,690.86L462.89,690.46L462.22,689.79L461.42,689.88L461.3,689.18L462.13,688.82L462.48,689.2L462.87,687.42L464.68,687.17L466.76,685.56L467.91,685.47L468.84,684.83L470.31,684.67L472.12,683.92L471.96,683.21L473.8,681.72L474.04,680.65L474.75,680.3L474.42,678.44L476.13,678.14L478.35,678.63L478.93,677.53L480.98,677.49L480.91,675.75L480.53,675.45L480.78,673.93L480.44,672.99L482.34,671.55L483,671.44z"
},
{
"id":"RU-IN",
"title":"Ingush",
"d":"M179.51,777.02L179.78,775.96L180.04,776.46L180.76,776.62L181.69,775.68L181.32,774.13L180.04,772.81L179.27,772.78L179.4,771.17L178.84,770.66L178.94,769.39L179.75,769.28L179.93,769.82L180.33,769.89L180.6,768.92L181.31,769.3L181.31,769.3L183.39,770.27L183.25,771.16L184.05,771.54L183.99,772.72L183.03,774.53L183.32,775.63L182.88,776.26L182.97,776.89L182.46,777.53L182.46,777.53L180.95,777.03L180.16,778.21z"
},
{
"id":"RU-IRK",
"title":"Irkutsk",
"d":"M713.08,600.94L709.84,601.58L708.46,600.91L707.4,599.4L706.62,598.83L705.88,598.64L705.3,598.91L703.74,598.22L703.13,598.25L702.56,599.03L701.42,599.5L701.17,600.07L701.91,600.62L702.22,602.03L701.77,602.21L701.24,601.63L700.86,602.22L701.02,603.02L700.57,604.82L700.78,605.35L700.42,605.45L700.21,606.03L698.97,605.97L698.62,606.37L699.06,606.67L699.31,607.54L698.92,608.3L699.3,608.92L700.15,608.99L699.56,610.28L699.81,610.89L700.41,611.3L700.41,612.72L700.99,612.67L701.12,613.16L700.72,613.76L701.17,614.15L702,613.57L702.11,613L702.57,612.94L703.79,613.57L703.31,613.82L703.01,614.78L702.24,615.12L702.86,616.25L702.47,617.79L702.09,617.98L702.27,618.64L701.95,619.27L701.48,618.96L700.99,619.21L699.98,617.76L699.17,618.56L698.79,619.53L698.5,619.71L697.82,619.48L697.94,620L697.18,619.9L696.42,620.45L696.07,620.13L694.27,620.02L693.13,619.01L692.72,618.94L691.92,619.49L691.11,618.73L689.52,617.85L689.2,617.95L689.2,617.95L691.81,615.72L692.67,615.39L691.68,614.17L689.57,614.29L688.26,615.68L684.31,615.75L684.3,617.13L682.88,619.27L682.48,620.66L682.08,621.01L680.49,621.03L679.86,621.54L677.72,621.21L676.71,622.25L676.45,623.08L676.05,623.18L675.2,623.01L674.93,622.27L673.49,621.49L671.15,621.94L668.56,621.04L667.21,619.71L667.13,617.88L666.53,617.82L665.3,619.2L663.77,618.93L662.84,618.02L661.59,617.84L661.19,618.33L660.81,618.24L659.39,615.84L658.91,615.64L657.84,616.58L657.2,617.8L657.26,618.41L655.93,619.66L654.96,619.11L653.75,619.24L653.11,618.96L651.9,619.35L650.54,618.23L647.82,617.7L647.15,618.6L646.89,620.13L645.63,621.22L644.18,620.92L642.19,621.71L641.33,621.66L640.21,622.75L638.51,622.99L638.31,623.32L638.69,623.56L638.62,624.21L637.54,625.91L638.49,627.04L639.51,627.44L640.45,629.96L640.97,629.92L642.23,630.68L641.85,631.28L640.6,631.12L639.86,631.36L638.79,635.19L638.3,635.55L638.47,636.41L638.05,637.08L638.13,639.14L638.23,639.59L638.84,639.99L638.39,642.08L638.6,643.57L638.33,644.41L638.4,646.89L637.91,647.29L637.34,648.6L637.86,648.58L637.41,649.18L637.15,654.94L634.22,663.74L630.35,667.56L622.82,672.05L614.66,681.58L609.85,684.26L609.28,685.3L609.3,686.73L608.82,687.24L608.39,686.96L607.75,687.37L606.35,687.53L605.89,688.08L604.82,688.31L604.25,688.91L603.51,689.11L603.51,686.19L602.47,685.42L600.1,685.42L599.47,684.82L599.18,683.76L599.32,682.5L598.63,680.65L596.64,679.72L595.23,677.74L594.76,677.54L594.59,676.34L593.57,675.9L592.77,676.14L591.46,675.79L590.67,676.27L589.48,675.16L588.37,674.66L587.78,673.23L586.12,671.55L582.58,669.36L581.67,668.04L579.41,666.51L578.82,665.54L578.78,663.9L578.13,662.34L577.25,662.61L576.94,663.38L575.23,663.21L575.17,664.42L573.44,665.51L571.67,665.76L571.68,666.4L570.82,667.04L570.53,667.99L570.53,667.99L568.15,666.55L568.68,665.92L568.06,665.47L567.57,665.36L566.95,665.73L566.26,665.3L565.65,665.8L563.35,665.99L563.24,664.67L561.82,664.44L561.32,663.79L561.31,662.95L560.24,662.85L559.69,662.48L558.37,662.68L558.13,661.89L557.08,661.3L556.84,660.57L556.19,659.93L555.04,659.93L554.7,659.43L554.14,659.29L553.36,658.21L552.34,658.29L552.24,659.18L552.24,659.18L550.58,658.79L549.86,657.65L549.2,657.24L548.16,655.39L547.39,654.93L547.35,654.22L545.87,653.16L545.33,652.36L544.52,652.21L544.65,650.92L545.33,650.02L546.71,649.78L547.59,648.19L550.75,648.56L550.69,647.93L551.94,644.61L551.85,643.72L551.33,643.14L551.96,640.65L551.59,639.52L553.4,638.7L552.73,637.5L552.86,635.22L552.18,634.63L552.48,634.21L552.37,632.96L553.68,631.75L553.96,629.99L554.89,629.88L555.16,628.89L556.05,629.01L556.46,629.5L557.28,628.67L557.37,627.44L558.13,627.5L558.01,625.31L560.54,624.98L560.36,624.04L560.67,623.13L560.53,622.84L559.56,622.7L559.88,619.94L557.79,619.81L557.51,619.35L557.6,618.76L558.43,618.31L558.63,617.65L556.64,616.58L560.79,606.57L566.88,606.8L567.32,607.57L568.98,607.48L569.49,606.86L570.15,606.99L571.63,606.65L572.09,604.55L572.81,604.08L573.07,602.98L574.04,602.76L574.79,603.15L575.71,602.76L576.53,603.57L575.98,604.67L576.24,605.82L576.62,606.16L578.05,606.46L577.97,606.99L578.52,607.47L578.26,608.23L578.83,608.83L578.5,609.28L578.67,610.02L580.15,610.86L580.49,611.65L580.96,611.68L581.49,610.83L582.14,610.99L582.46,610.67L582.29,609.7L581.7,609.34L581.35,608.26L581.76,606.9L581.33,605.51L583.19,605.61L583.21,604.81L584.44,603.35L583.84,602.99L583.93,602.41L585.82,600.83L586.74,600.63L587.81,598.23L588.4,597.69L591.11,597L592.41,595.24L593.64,594.56L594.1,593.72L593.92,591.83L592.85,589.66L593.42,587.95L594.95,587.2L595.93,587.4L596.11,586.8L596.93,586L597.88,586.49L598.56,586.17L599.85,586.34L599.88,586.78L598.99,586.79L598.96,587.64L599.75,588.61L599.78,589.33L601.08,590.93L604.02,591.76L604.19,593.84L605.26,593.32L606.27,593.46L606.38,594.14L606.99,594.25L606.91,595.46L608,595.67L608.46,595.31L609.33,595.3L610.9,593.92L610.36,593.52L609.97,592.63L610.15,592.03L612.57,589.76L613.75,589.36L614.21,588.87L614.05,587.06L612.85,585.81L613.21,585.16L613.1,584.06L612.08,584.08L610.88,582.74L610.74,581.78L610.17,580.84L611.82,579.53L612.47,578.21L615.6,578.33L615.55,577.73L614.97,577.17L615.37,576.02L615.03,575.22L615.17,572.37L614.49,572.51L613.95,571.91L612.7,572.08L610.69,570.91L608.9,568.83L608.3,567.46L608.98,565.87L608.73,565.32L608.15,565.16L608.1,564.5L608.93,564.07L608.87,561.84L609.17,561.06L609.94,560.71L609.98,560.06L612.15,558.84L611.93,557.83L611.38,557.24L611.47,556.54L613.83,555.47L613.96,554.89L616.15,553.2L616.49,552.52L617.84,552.5L618.85,551.73L618.41,549.78L621.8,546.54L622.35,543.95L621.91,543.55L621.86,543.05L622.48,542.27L622.64,541.51L624.58,539.44L624.49,538.63L625.02,537.73L623.19,537.2L622.69,536.51L623.01,535.68L622.02,533.96L620.69,532.69L620.48,530.76L621.56,530.65L622.07,530.28L622.42,528.52L621.78,527.8L622.06,526.79L622.66,526.48L623.42,527.05L624.16,526.65L624.56,525.99L623.3,524.3L622.99,523.42L623.9,522.18L624.02,520.14L624.67,518.44L624.19,516.22L624.5,515.92L627.21,517.39L628,516.42L629.06,517.51L630.18,517.7L630.71,517.34L630.99,516.23L632.25,515.88L635.08,515.74L635.65,516.38L636.58,514.4L635.63,513.3L635.18,511.8L634.07,511.28L634.07,511.28L634.86,510.84L635.87,511.26L636.71,510.42L637.09,510.53L637.15,511.65L637.67,512.08L637.29,513.04L637.62,514.48L637.92,515.11L639.1,515.31L639.58,516L639.26,517.45L639.65,517.73L639.68,518.31L639.06,518.94L636.15,519.14L636.15,520.21L634.99,522.33L635.28,523.03L636.98,522.45L638.12,522.41L639.99,523.35L641.46,523.14L642.93,526.08L643.84,525.8L644.35,532.17L644.65,532.96L645.71,534.16L645.64,534.65L644.41,535.81L644.15,537L643.61,537.38L643.58,537.98L643.05,538.46L643.05,539.76L644.13,541.33L644.97,540.76L647.09,540.72L647.8,542.61L647.49,543.12L647.9,544.42L647.3,545.62L647.39,546.46L646,547.17L645.37,547.96L644.83,549.58L645.2,551.24L646.84,553.82L646.54,557.14L646.88,557.81L647.35,557.97L648,557.68L648.47,558.04L648.95,559.21L649.8,559.82L651.02,559.64L651.81,560.21L651.5,562.37L649.83,564.7L650.19,565.39L649.76,566.41L648.42,566.64L648.33,567.05L648.89,567.48L648.85,567.91L648.18,568.21L648.08,568.84L647.32,569.5L647.42,570.54L646.74,571L646.48,572.15L645.89,572.91L645.46,574.8L645.98,575.9L645.13,577.21L645.12,578.18L643.72,580.28L644.04,581.15L643.77,582.11L642.53,583.58L642.34,584.29L642.76,584.61L642.28,585.12L642.15,585.85L643.51,586.5L643.72,587.38L644.59,588.42L644.5,589.48L644.82,589.79L645.6,589.44L645.93,590.72L646.82,590.39L649.52,590.52L650.39,589.99L651.1,589.93L651.71,589.28L652.21,587.59L652.67,587L654.56,587.3L655.45,587.03L655.88,587.6L656.48,587.66L656.82,587.06L658.18,586.72L659.27,587.5L659.98,586.75L661.99,586.24L663.91,583.56L664.51,584.56L664.2,586.45L665.16,586.02L666.62,586.01L666.6,587.2L665.71,587.63L664.97,588.44L665.16,589.8L664.85,591L665.12,592.42L665.63,592.44L666.12,592.09L666.12,589.48L666.63,589.08L666.64,589.85L667.41,590.4L668.36,588.85L670.43,588.07L671.23,588.16L672.67,586.84L672.82,586.11L672.43,584.68L673.45,583.89L673.73,582.77L674.54,581.96L675.32,581.89L675.35,581.32L675.7,580.8L676.38,580.74L676.3,580.14L676.68,579.82L677.19,580.07L677.71,579.88L677.7,579.04L678.29,578.2L679.73,577.03L680.51,576.87L680.66,576.15L680.31,575.37L681.57,573.57L682.98,573.62L683.54,573.3L684.09,572.33L684.35,570.8L685.37,569.32L685.88,569.76L686.65,569.75L688.6,568.61L689.15,568.6L690.04,569.23L689.98,569.79L691.18,569.79L691.94,570.19L691.97,570.67L692.78,570.68L693.08,571.21L694.49,571.07L695.22,572.04L696.08,572.22L696.17,572.98L697.22,573.33L697.78,573.95L698.13,574.53L698.18,575.62L698.53,576L700.08,575.62L699.51,577.24L698.86,577.5L698.38,578.13L699.03,578.75L699.13,581.42L698.9,582.15L699.17,582.83L700.04,583.5L701.43,583.33L702.14,583.63L703.19,582.8L703.56,584.14L703.95,584.48L704.72,584.11L704.95,582.79L705.42,582.53L705.78,581.54L705.92,582.03L706.94,581.77L707.62,582.57L707.9,583.57L710.57,584.5L711.2,586.16L710.22,587.52L710.6,590.2L711.08,590.51L710.63,591.47L711.13,593.02L710.76,595.88L712.99,597.35L713.08,598.06L712.69,598.64L713.32,600.24z"
},
{
"id":"RU-IVA",
"title":"Ivanovo",
"d":"M149.56,613.56L150.26,613.14L150.97,613.31L151.21,612.93L152.57,612.75L153.4,613.24L153.4,612.82L153.81,612.84L154.27,612.24L154.27,611.69L154.79,611.95L157.51,611.1L157.82,609.41L157.58,607.85L159.99,608.58L160.12,609.06L161.28,609.75L161.65,609.45L162.04,609.7L162.88,609.55L163.09,609.05L163.72,608.78L164.01,609.05L165.22,608.88L165.51,608.18L166.35,608.47L166.1,609.7L166.48,610.74L165.86,611.34L166.64,612.13L167.76,612.24L168.53,611.74L168.74,611.27L168.45,609.91L168.98,608.96L169.18,611.57L170.11,610.39L170.86,610.07L172.13,610.34L172.58,610.74L172.71,611.37L172.71,611.37L172.6,611.84L173.74,612.52L173.63,612.82L173.29,612.59L173.09,613.16L172.65,612.84L172.15,613.2L172.34,613.64L171.48,614.04L171.13,614.58L171.06,615.8L171.96,616.02L171.91,616.28L172.41,616.5L171.18,618.84L168.37,619.18L168.34,619.52L167.86,619.75L167.29,619.43L166.49,619.75L166.06,620.33L166.44,620.83L166.06,621.72L166.41,622.01L166.81,621.7L166.86,624.18L165.18,624.25L164.76,625.06L164.76,625.06L163.54,625.14L163.37,624.62L162.33,624.39L161.66,624.58L161.62,625.14L160.74,625.9L159.84,625.52L159.6,623.86L157.51,624.47L156.96,624.92L156.51,624.29L155.01,624.2L154.77,623.85L154.04,624.15L153.85,624.56L153.38,624.11L152.07,623.78L151.82,622.8L151.16,622.59L149.59,623.01L149.42,623.38L148.72,623.43L148.58,623.8L148.23,623.7L147.58,625.01L146.93,624.48L146.02,624.29L145.34,622.44L144.7,622.38L145.21,621.24L145.15,620.38L143.36,619.82L142.35,620.5L141.95,620.43L141.95,620.43L141.77,619.43L142.15,619.44L142.32,618.55L143.17,618.2L142.67,617.41L143.09,616.96L143.49,616.97L143.45,616.57L144.49,615.95L144.67,616.13L145.35,615.21L145.76,615.19L146.3,614.61L146.61,614.48L147.11,614.97L147.47,614.91L147.46,614.5L147.96,614.17L147.23,613.73L148.97,613.9z"
},
{
"id":"RU-KB",
"title":"Kabardin-Balkar",
"d":"M166.62,767.19L169.62,766.38L170.17,765.9L170.9,767.27L172.31,766.85L173.83,767.29L174.43,766.02L175.18,765.46L177.49,766.34L178.39,765.21L178.43,765.74L177.72,766.68L177.7,767.38L177.7,767.38L177.63,768.14L178.47,768.93L178.28,771.16L178.07,771.35L177.41,771.07L176.69,771.57L175.97,771.23L175.69,771.55L175.85,772.59L175.47,773.03L175.1,772.96L174.95,772.72L175.31,772.67L175.04,772.33L174.57,772.57L174.18,771.97L172.19,775.23L171.54,775.52L170.97,775.16L170.48,775.58L170.48,775.58L168.86,775.2L167.77,774.23L167.76,773.68L166.95,773.43L166.72,772.9L165.19,772.86L165.21,773.22L164.26,772.75L164.26,772.75L163.96,772.04L164.06,771.04L164.63,770.25L164.52,769.27L166.23,768.25z"
},
{
"id":"RU-KC",
"title":"Karachay-Cherkess",
"d":"M159.38,760.31L159.75,759.99L160.53,760.07L161.26,761.27L163.59,761.72L164.38,762.54L164.42,762.04L165.13,762.09L165.2,761.49L165.51,761.41L166.26,762.57L163.88,763.87L163.59,764.92L164.78,765.61L165.14,765.42L165.05,764.88L165.57,765.01L166.12,765.93L166.23,766.94L166.62,767.19L166.62,767.19L166.23,768.25L164.52,769.27L164.63,770.25L164.06,771.04L163.96,772.04L164.26,772.75L164.26,772.75L163.57,772.48L163.44,772.07L162.38,772.52L161.84,772.31L160.73,772.66L159.4,772.14L159.02,772.57L158.42,772.28L157.67,772.38L156.2,771.57L156.07,771.02L155.52,771.3L154.14,770.69L153.58,770.81L153.12,770.33L152.68,770.39L152.28,769.8L151.11,769.35L151.11,769.35L151.16,767.38L151.85,765.59L152.67,765.27L152.73,763.77L153.3,763.54L155.86,764.24L156.33,765.08L157.13,765.24L157.69,764.16L158.34,764.16L158.94,762.85L158.86,761.99L158.16,761.23z"
},
{
"id":"RU-KDA",
"title":"Krasnodar",
"d":"M159.38,760.31l-1.22,0.91l0.71,0.76l0.08,0.86l-0.6,1.31l-0.65,0l-0.56,1.08l-0.8,-0.15l-0.47,-0.84l-2.56,-0.7l-0.57,0.22l-0.06,1.5l-0.82,0.32l-0.68,1.79l-0.05,1.97l0,0l-0.38,-0.28l-0.65,0.43l-2.32,-0.67l-1.02,0.16l-0.68,1.81l-0.43,-0.13l-0.51,-0.99l-1.07,-0.69l-3.13,-3.7l-1.86,-1.53l-0.27,-0.65l-0.95,-0.35l-0.53,-0.84l-4.23,-1.36l-1.1,-1.33l0.12,-0.26l-0.58,0.09l-0.58,-0.64l0.07,-0.36l-0.8,-0.68l0.07,0.55l-0.53,0.3l-1.83,-0.45l-0.75,-0.65l-0.58,-1.33l0.13,-0.37l-0.56,-0.64l-2.4,-1.16l-1.2,-0.04l-0.99,-0.87l2.83,-0.94l0.03,-0.39l-1.42,0.24l-0.24,-0.74l0.26,0.22l0.39,-0.25l-0.66,-0.36l0.15,-0.28l0.51,-0.09l2.65,1.21l1.6,-0.14l0.69,-0.44l0.43,-0.9l0.06,-1.9l1.57,-0.94l1.01,-2.87l1,-0.21l-0.33,0.89l0.29,0.19l0.56,-1.7l0.42,-0.43l1.54,1.17l0.88,0.05l-0.09,-0.78l-1.59,-0.98l-1.47,-1.73l-1.02,-0.34l-0.06,0.47l-0.54,-0.45l-1.35,-2.91l0.68,0.43l1.28,0.12l2.09,-1.11l0.24,0.78l1.3,0.25l0.64,-0.25l-0.11,-0.6l-1.25,-0.3l0.12,-0.76l0.56,-0.57l0.34,0.25l0.81,-0.17l0,0l0.11,0.42l1.52,-0.03l-0.64,1.46v0.69l0.5,-0.59l1.5,0.12l0.72,-0.68l0.08,-0.67l1.39,-0.79l0.54,0.41l3.36,0.35l0.71,0.54l-0.49,1.73l1.5,0.67l0.43,0.98l-0.25,0.54l0.66,0.81l2.7,0l0.75,0.57l1.34,-0.51l0.2,1.34l0.78,0.52l0.68,1.31l0,0l-0.15,0.74l0.68,0.53l0.2,0.98l-0.55,0l-0.49,0.92l-0.76,-0.35l-1.12,0.22l-0.22,1.27l0.7,0.45l0.68,1.05l0.28,1.86l2.46,0.3l-0.02,0.89l0.89,1.23l1.4,0.75l0.08,1l-0.92,1.14l-0.78,0.3l0.54,0.94L159.38,760.31zM144.58,762.42l1.01,1.4l1.07,-0.59l-0.04,-1.25l-0.44,0l-0.33,-0.63l-0.5,0.02l-0.37,-0.38l0.25,-0.8l-0.39,-1.32l0.57,-0.54l-0.02,-0.74l0.95,-0.62l-0.67,-0.47l0.37,-0.39l-0.16,-0.56l-0.61,-0.22l0.22,-0.57l-1.21,-0.08l-0.65,-0.57l-0.64,1.99l-1.16,0.37l-1.89,-0.38l-1.11,0.12l-1.37,-0.57l-0.66,-0.69l-0.84,-0.14l-0.22,-0.44l0.44,-0.57l0.48,0.44l0.8,-0.14l1.03,0.64l1.66,-0.1l2.02,-0.9l1.08,-0.86l1.17,0.2l0.67,0.61l1.11,0.4l0.81,-0.4l1.14,0.07l1.44,1.2l2.25,5.05l-0.65,0.26l-0.92,-2.54l-0.49,-0.46l-0.7,0.06l-0.53,1.54l1.03,2.29l-0.6,1.71l0.47,1.84l-0.38,1.26l-1,0.86l-2.53,-1.55l-1.48,0.1l-0.6,-0.52l0.67,-0.31l-0.17,-0.54l0.54,-0.24l-0.58,-1.01l0,0L144.58,762.42z"
},
{
"id":"RU-KEM",
"title":"Kemerovo",
"d":"M494.56,618.98L495.08,621.16L494.98,621.97L494.65,622.31L493.99,622.37L493.74,623.12L494.57,623.8L494.45,624.35L495.31,625.67L496.43,625.65L496.83,626.5L497.84,626.57L498.15,627.88L499.16,629.07L499.1,630.07L499.75,631.8L500.48,632.14L500.36,633.07L499.23,633.59L498.71,634.29L497.05,634.68L494.72,637.57L494.72,637.57L494.72,637.57L494.72,637.57L494.27,638.54L493.56,638.88L493.55,639.66L494.1,642.85L494.83,644.28L495.64,645.01L495.38,645.94L494.7,646.26L494.41,646.98L494.08,649.96L492.88,650.59L493.13,651.02L494.41,651.74L494.88,651.54L495.38,650.61L496.27,650.35L496.66,651.36L497.1,651.64L498.29,651.08L498.5,651.32L498.78,653.1L497.79,654.25L497.55,655.81L498.46,655.91L498.93,657.98L497.54,658.32L496.87,659.85L495.98,660.7L496.25,661.57L495.69,663.16L495.8,663.52L496.44,662.89L497.34,664.24L497.55,664.76L496.99,665.03L497.67,665.56L497.73,666.09L496.89,666.53L496.72,667.37L496.98,667.82L497.44,667.74L497.99,668.76L498.71,669.1L498.92,669.74L498.44,669.84L498.17,670.47L497.57,670.82L497.45,671.3L498.24,672.14L496.76,673.63L495.06,674.73L495.18,675.79L493.85,676.73L493.19,676.86L493.19,676.86L493.35,675.05L493.02,674.13L492.19,673.9L491.35,674.2L489.57,672.61L489.11,672.65L488.02,673.93L487.54,673.98L485.28,673.06L485.4,672.61L485.11,672.12L484.16,672.34L483.82,672.01L483.82,672.01L483.81,671.18L483.58,670.85L482.91,670.9L482.59,669.81L482.61,669.01L483.18,668.44L483.04,667.17L480.82,665.32L480.32,664.57L480.48,664.19L481.89,663.52L482.29,662.6L482.3,661.63L479.5,661.28L479.07,660.21L478.37,659.64L477.76,657.71L477.15,657.41L476.6,655.7L475.2,655.03L475.11,654.67L474.46,654.4L474.11,653.62L472.35,652.65L471.44,652.82L470.01,650.37L469.66,650.1L469.26,650.25L469.26,650.25L468.46,648.28L469.01,647.51L468.18,646.73L468.32,646.09L468.87,645.91L469.21,645.39L468.92,644.4L467.77,643.08L468.15,641.53L467.74,639.9L467.8,638.21L466.06,638.15L467.12,637.33L467.32,635.76L467.06,635.15L466.21,634.78L465.55,633.64L465.73,633.27L465.28,631.83L465.6,631.39L465.42,630.2L464.77,630.01L464.77,630.01L467.25,628.55L468.34,628.63L470.5,627.7L473.16,627.48L472.76,627.33L472.54,626.65L474.06,626.16L474.42,625.19L475.8,624.46L476.39,623.77L476.95,623.71L477.2,622.32L477.49,622.09L478.45,623.1L478.89,623.17L480.18,622.34L481.65,622.36L481.42,623.17L481.64,623.43L483.15,623.36L484.02,622.99L484.25,622L485.61,621.99L485.54,622.87L487.13,621.95L487.47,623.44L489.1,622.75L490.37,621.58L493.1,619.83L494.06,620.13z"
},
{
"id":"RU-KLU",
"title":"Kaluga",
"d":"M112.83,640.04L113.17,640.46L113.93,640.49L114.77,639.73L115.69,639.61L116.39,640.37L117.22,640.28L117.67,640.77L118.29,640.7L118.54,641.09L119.29,640.88L119.45,641.13L119.99,640.04L120.25,640.06L120.35,639.47L121.24,639.49L121.66,639.02L121.89,640.06L122.99,640.1L123.17,640.7L124.35,640.24L124.35,640.24L124.34,640.26L124.34,640.26L124.34,640.26L124.34,640.26L124.34,640.26L124.34,640.26L124.41,640.44L124.41,640.44L124.41,640.44L124.41,640.44L124.41,640.44L124.41,640.44L124.42,640.44L124.42,640.44L124.44,640.46L124.44,640.46L124.47,640.51L124.47,640.51L124.46,640.53L124.46,640.53L124.45,640.54L124.45,640.54L125.05,641.35L125.05,641.35L125.19,641.3L125.19,641.3L125.41,641.28L125.41,641.28L125.11,641.38L125.09,641.75L125.56,641.95L125.57,642.38L125.31,642.49L125.97,643.61L125.92,644.84L126.17,645.04L126.17,645.04L125.79,647.69L125.26,648.68L124.53,648.02L123.72,648.23L123.97,648.81L123.34,649.24L123.55,649.96L124.27,650.07L124.06,651.41L124.32,651.79L122.37,651.94L121.95,651.61L120.93,651.9L120.3,652.65L119.5,652.46L118.78,653.43L117.6,653.25L118.41,653.71L118.27,654L117.64,654.08L119.04,654.25L118.33,655L118.34,656.07L117.75,655.94L117.18,656.42L117.44,656.82L116.76,657.21L117.12,657.7L116.77,658.14L117.81,659L117.27,659.6L117.27,659.6L116.16,660.44L115.92,660.98L115.22,661.04L114.99,660.62L114.42,661L113.92,662.24L113.58,662.14L113.92,661.4L113.44,661.56L112.92,662.93L111.97,663.26L112.02,663.78L111.64,663.58L111.03,663.85L111.03,663.85L110.25,662.91L109.29,663.04L108.11,662.48L107.44,662.48L106.76,661.96L106.6,659.06L105.86,658.6L105.86,658.11L104.8,657.33L104.6,656.8L103.25,657.22L102.97,656.87L102.61,657.02L101.78,655.56L100.81,654.97L99.68,655.13L99.68,655.13L99.25,654.44L99.97,654.33L100.22,653.16L100.73,652.91L100.47,652.42L101.15,651.43L100.5,650.95L100.88,650.04L100.5,649.78L100.81,649.1L101.25,649.17L102.05,648.41L102.25,648.74L102.49,648.42L103.08,648.38L103.97,648.81L104.53,648.69L104.85,649.29L105.32,648.99L106.48,649.15L106.96,647.71L106.25,646.74L107.79,647.14L109.78,646.01L109.97,645.73L109.41,645.23L109.33,644.63L110.99,642.93L111.3,643.51L111.47,643.38L111.96,642.02L112.2,642.03L112.85,640.88z"
},
{
"id":"RU-KHA",
"title":"Khabarovsk",
"d":"M798.39,634.07l-0.01,-1.12l-0.6,-0.92l-0.06,-0.77l0.59,-1.96l1.3,-2.3l0.18,-2.26l0.59,-0.89l0.57,-0.2l0.59,0.65l0.46,-0.1l0.57,-0.89l0.68,0.97l0.58,-0.16l0.27,-0.48l-0.55,-0.96l0.09,-1.48l0.99,-0.69l0.14,-0.55l-2.6,-4l-1.08,-1.02l-0.71,-0.08l-0.26,-0.95l0.53,-0.12l0.21,-0.94l0.39,-0.06l-0.01,0.39l1.08,0.54l0.39,-0.25l0.45,-0.87l0.03,-1.06l1.12,-1.38l0.1,-0.54l0.8,-0.72l0.57,-0.05l0.14,-0.61l0.41,-0.08l0.26,-0.5l-2.23,-2.36l0.37,-0.67l-1.13,-0.46l-0.55,-0.67l0.18,-0.84l-0.7,-0.17l-0.16,-1.15l1.33,-0.32l0.53,0.83l1.2,0.5l0.56,0.67l1.04,-0.06l-0.45,-1.86l0.37,-0.77l0.53,-0.19l-0.46,-3.33l1.81,0.23l0.25,-0.96l0.68,-0.83l-0.38,-0.97l0.74,-2.39l1.61,-0.33l0.32,-0.77l-0.68,-0.7l0.44,-1.15l0.55,0.15l0.61,-0.27l0.24,-1.04l0.64,-0.32l0.95,0.17l1.93,-0.8l0.86,0.49l2.47,-0.54l1.74,0.91l0.65,-0.21l0.76,0.68l0.77,0.01l0.85,-0.71l0.41,0.03l0.88,1.05l0.43,-0.16l1.75,0.67l0.65,-0.35l0,-0.36l0.71,-0.76l-0.01,-0.9l2.25,-3.08l0.8,-0.23l1,0.17l1.44,0.82l0.09,0.39l1.79,0.56l1.58,0.11l1.12,0.69l0.5,-0.04l1.3,-1.22l1.54,-0.26l1.99,-1.83l0.3,-0.47l-0.14,-0.92l1.17,-1.18l2.61,0.04l0.48,-0.41l0.29,0.66l-0.15,0.8l0.82,-0.03l0.57,-0.69l-0.03,-0.32l-0.52,-0.28l-0.18,-1.2l0.75,-1.17l-0.57,-0.72l0.16,-1.37l-0.32,-0.85l0.27,-0.45l0.01,-1.32l1.07,-1.98l-0.45,-1.09l1.41,-3.35l-2.19,-2.59l1.05,-2.4l-0.26,-0.74l0.22,-0.32l0.66,0.16l1.71,-1.5l0.31,-0.56l-0.33,-0.87l0.43,-0.76l0.36,0.55l0.48,-0.37l1.37,-0.01l0.38,-0.45l-0.02,-0.85l0.46,-0.48l0.93,0.31l0.96,-0.7l1.38,-0.3l1.02,-1.79l0.64,-0.3l1.23,-3.64l-0.36,-1.14l0.66,-0.33l1.35,0.08l0.09,-0.54l0.69,-0.76l-0.43,-0.65l0.69,-4.5l0.66,-0.51l1.45,-0.05l0.71,-1.35l1.01,-0.01l0.43,0.78l0.9,-0.05l-0.04,1.01l0.82,0.06l0.67,-0.33l0.17,0.86l0.74,1.12l0.85,0.53l-0.03,1.03l0.47,0.7l0.66,0.34l0.14,0.5l0.87,0.23l0.52,1.04l1.01,-0.35l0.42,-0.59l0.72,-0.02l0.45,1.88l1.11,0.78l0.77,-0.1l0.92,-1.05l1.79,0.52l0.26,0.75l0.63,-0.22l0.08,-0.83l0.79,-0.95l-0.05,-1.23l0.92,-0.39l0.04,0.8l0.68,0.48l-0.04,0.38l0.86,-0.52l0.66,0.14l0.33,0.77l-0.26,0.37l0.86,1.55l0.58,-1.17l1.1,-0.58l0.41,0.18l-0.31,0.94l0.24,0.71l-0.44,0.72l0.13,0.63l0.78,0.42l0.47,-0.34l1.08,-0.04l0.77,-1.04l1.14,-0.4l0.53,-2.21l0.86,-0.86l0,0l1.78,-0.21l0.56,0.9l1.29,0.76l0.52,-0.79l0.39,0.08l0.27,0.46l0.49,-0.12l-0.26,0.78l0.58,0.01l0.21,-0.48l0.59,-0.09l0.34,-0.48l-0.13,-0.86l0.42,-0.34l0.42,0.95l1.04,0.18l1.93,1.33l2.08,2.82l-0.03,0.71l1.14,1.42l-0.14,1.77l0.79,0.99l-0.24,1.02l0.74,2.26l-0.05,1.23l-0.41,0.52l0.15,0.35l-0.49,1.41l-1.15,0.13l-0.32,0.46l-0.02,2.12l0.37,0.68l-0.36,0.65l-0.76,0.02l-1.43,-1.18l-0.5,0.13l-0.47,0.54l-0.51,0.05l-0.54,1.19l-0.5,0l-1.08,0.79l0,0.88l-0.68,0.19l-0.23,0.61l0.68,1.04l-0.53,0.26l2.27,2.46l1.03,-0.55l0.96,0.26l0.99,-0.58l0.85,0.26l0.73,1.55l1.44,0.32l0.26,0.77l-0.45,0.73l0.81,1.35l0.34,0.11l0.87,-0.87l0.57,-0.05l0.05,0.89l0.84,0.34l0.11,0.65l-0.37,0.4l0.45,0.44l0.16,1.68l-0.57,1.41l-0.02,1.82l-1.67,0.65l0,0l-0.8,0.14l-1.08,-0.42l-0.17,-0.61l-1.67,-0.42l-1.01,1.01l0,1.62l0.35,0.97l-0.28,0.29l-0.79,-0.33l-1.11,0.95l-0.49,-0.05l0.08,-0.51l-1.17,-0.91l1.03,-2.22l-0.34,-0.25l-0.33,0.34l-0.36,-0.2l-0.17,0.67l-0.78,-0.85l-0.1,0.22L903,584.4l-1.83,0.5l-0.01,-0.34l-0.45,-0.1l-2.08,0.67l-7.81,-0.45l-2.83,1.15l-1.64,-0.6l-5.9,2.39l-2.73,2.5l-2.63,4.56l-0.84,0.95l-1.77,1.45l-2.06,0.93l-1.83,1.88l-1.58,4.04l-0.45,2.16l-1.01,0.7l-0.3,0.59l-0.47,-0.25l-1.71,0.81l-1.53,2.94l-0.51,-0.1l-0.77,0.37l-0.85,1.71l-1.33,0.78l-0.88,0.06l-0.97,1.08l-0.15,0.71l-0.24,-0.24l-0.42,0.16l-0.25,1.49l-0.34,0.24l-0.43,-0.24l0.03,0.33l-1.37,0.67l-0.23,2.23l-0.24,-0.16l0.05,-0.8l-0.84,0.18l0.25,0.38l-0.66,1.23l-0.67,0.36l-0.08,0.95l-0.32,-0.1l-0.83,0.64l0.16,1.1l0.86,0.31l-0.2,0.56l-0.44,-0.3l-0.71,0.12l-0.16,0.78l-0.92,0.19l-0.54,1.68l-0.45,0.22l-0.4,1.05l-0.98,0.25l-1.14,1.03l-0.25,1.16l-0.67,-0.25l-1.49,1.39l-0.27,0.87l-0.56,-0.08l-0.88,0.69l-0.68,1.22l-0.3,-0.31l-0.82,0.69l-0.35,-0.15l-0.08,0.54l-0.86,0.19l-2.05,3.52l-0.51,0.03l-1.15,1.21l-0.62,0.06l-0.8,0.86l-1.31,0.41l-2.43,2.73l-0.04,0.59l0.61,0.97l2.25,0.97l0.65,0.01l0.26,0.17l0.03,0.76l0.56,0.37l3.08,-0.76l0.28,0.25l1.85,0.09l2.3,-0.71l-0.19,0.57l0.57,0.42l-0.57,0.63l0.34,0.32l-0.35,0.28l0.19,0.51l-0.24,0.28l-0.06,-0.4l-0.31,0.24l0.05,0.7l0.5,0.42l-0.51,0.42l0.4,0.33l0.04,0.29l-0.43,0.24l0.49,0.99l-0.34,0.13l0.22,0.15l-0.12,0.61l-0.62,0.59l-0.19,1.18l0.26,1.43l0.62,0.46l0.48,-0.47l-0.05,-0.34l0.66,-0.32l0.88,0.1l0.35,0.47l0.59,-0.51l0.77,-2.24l-0.26,-0.24l-0.77,0.21l-0.54,-1.08l0.75,-1.05l0.72,-0.18l-0.18,-0.26l0.82,-0.34l0.11,-0.38l1.72,0.14l0.71,-0.33l-1.87,2.77l-0.21,0.09l0,-0.75l-0.55,0.13l-0.39,0.26l-0.19,0.78l1.02,0.17l1.16,1.04l1.89,-0.15l-0.38,0.75l-1.4,0.85l-0.07,0.72l-0.72,1.26l-1.21,0.13l-0.98,0.88l0.86,0.63l4.58,-0.58l2.53,-1.83l0.49,-2.08l1.51,-1.1l-0.1,2.34l-1.53,1.87l0.07,0.5l-0.73,0.51l0.04,0.54l1.41,-0.09l1.4,-2.21l0.37,-2.46l0.41,-0.85l0.01,-1.34l-0.78,0.4l0.47,-1.08l0.06,-1.22l-0.56,-0.47l0.64,-0.22l1.97,1.09l2,0.47l1.21,-0.3l1.92,-1.16l0.36,0.07l0.04,1.1l2.89,1.77l0.08,0.69l0.87,0.53l-0.53,0.76l0.4,1.08l1.49,1.12l-0.08,0.39l0.89,0.92l2.2,1.24l-0.24,0.89l0.64,-0.22l-0.07,0.41l0.91,0.17l-0.18,0.28l0.75,0.66l1.63,0.26l-0.16,0.58l-0.37,0.19l0.52,0.06l0.21,0.88l-0.58,0.19l0.04,0.64l-1.06,0.15l0.27,0.33l-0.4,0.49l-0.72,0.05l-1.63,-0.99l-0.4,-0.67l-0.71,0.08l0.78,1.06l0.73,0.04l0.18,1.15l0.62,0.18l0.13,0.48l1.29,0.21l-0.55,0.88l0.6,0.65l0.15,1.71l-0.39,0.98l-0.73,0.29l0.07,0.98l1.91,2.1l1,-0.18l0.13,0.98l-0.59,-0.08l-0.82,0.71l-0.03,1.17l0.56,0.5l-0.23,0.48l-1.42,0.77l-0.62,1.92l-0.7,0.02l-0.95,0.59l0.07,1.53l-1.14,0.35l0.4,0.11l0.08,0.45l0.49,-0.07l-0.03,0.58l-1.37,0.58l0.25,0.81l-0.53,0.21l0.37,2l-0.35,0.7l0.13,0.39l-0.9,0.68l-0.09,0.94l-0.6,1.14l0.46,0.99l-0.57,0.97l0.85,2.28l-0.28,0.44l0.1,1.61l0.26,0.42l1.03,0.33l-1.44,1.03l-0.62,1.27l0.34,0.82l0.58,0.25l-0.21,1.17l0.34,1.28l-0.92,1.76l0.05,1.16l-0.82,0.9l0.25,0.14l0.04,1.09l-0.5,0.11l0.24,0.46l-0.68,0.91l0.82,-0.6l0.41,0.53l-0.21,0.61l-0.88,0.81l-0.4,1.04l-0.06,3.28l-0.64,0.46l-0.35,0.77l-0.81,0.33l-1.44,1.48l-1.31,2.06l-0.95,0.48l-0.92,1.16l-1.63,3.64l0.02,0.69l-0.34,-0.12l0,0l-1.02,-0.72l-1.22,0.32l-1.21,-0.39l0.56,-1.33l-0.54,-0.59l0.12,-0.37l1.61,-1.02l0.12,-0.73l-0.46,-0.91l-1,-0.86l0.37,-0.79l0.57,-0.21l-0.03,-0.56l-1.11,-0.14l0.06,-0.53l-0.54,-0.37l-0.29,-1.49l-1.12,-0.34l-0.91,0.73l0.03,0.65l-1.51,0.26l-0.29,0.61l-1.06,0.46l-0.95,-0.31l-1.13,0.31l-1.03,1.02l0.55,1.15l1.34,0.79l-0.17,0.49l-0.79,0.26l-0.18,0.51l1.21,0.09l1.25,0.89l0.95,-0.21l0.61,0.43l0.45,-0.06l-0.51,0.75l0.62,0.23l0.09,1.09l-0.58,0.56l-0.56,0.08l-0.06,0.7l-0.79,0.38l-0.73,-0.26l-2.04,1.64l-0.86,-0.3l-0.17,-0.37l-1.64,-0.34l-0.77,2.14l0.39,0.85l-2.81,2.16l-1.04,-0.16l-0.87,0.48l-1.33,-0.5l-0.35,-0.58l-0.35,0.03l-0.58,0.77l-1.58,-1.17l0.21,-0.47l-1.19,-0.08l-0.01,-0.23l-0.35,0l-0.49,0.58l-0.68,0.03l-0.09,-0.38l0.5,-0.83l-0.66,-0.46l-0.06,-0.86l-0.85,-0.03l-1.05,-0.49l-0.73,0.84l-0.72,-0.27l-0.46,0.33l-0.95,-0.01l-0.6,1.79l-0.98,-0.46l0.31,2.15l-0.33,0.81l-3.23,0.72l0,0l0.35,-3.22l0.49,-1.21l0.62,-0.32l-0.04,-0.82l-0.47,-0.53l0.23,-0.81l0.82,-1.03l1.42,-0.24l0.53,-0.53l1.48,-2.49l-0.71,-0.99l-0.13,-0.75l-0.49,-0.14l-0.27,-0.93l1.15,-3.02l-0.59,-0.26l-0.43,-0.72l-0.42,0.21l-0.77,-0.41l-0.8,0.12l0,0l1.61,-1.13l1.73,0.52l0.72,-0.45l0.24,-1.3l-0.87,-0.31l-0.57,0.32l-0.67,-0.46l-0.26,0.33l-0.41,-0.84l-0.44,-0.08l-0.44,-0.59l-0.47,-0.04l-1.08,1.11l-3.09,-0.5l-2.37,-1.07l-1.17,-1.24l-0.68,-3.08l-0.87,-0.48l-1.69,-0.12l-0.34,-0.89l-0.63,0.33l-0.7,-0.21l-0.62,0.35l-0.57,-0.44l-0.07,-1.03l-1.64,-0.84l-0.78,0.33l-0.16,0.78l-0.38,0.23l0.04,0.79l-0.48,0.12l-0.36,-0.46l-0.73,-0.17l-1.95,1.27l-0.67,-0.29l0,0l0.44,-0.14l0.43,-1.36l-0.01,-1.95l-0.75,-1.3l0.92,-1.27l-0.2,-0.31l0.27,-0.94l-0.42,-0.6l-0.01,-0.95l-0.51,-0.38l0.65,-0.95l-0.59,-1.18l-0.78,-0.25l-0.19,-1.06l-0.45,0.24l-0.49,-0.4l-0.65,-0.12l-0.52,0.32l-0.46,-0.33l0.07,-0.52l0.7,-0.82l-0.02,-0.62l-0.6,-0.94l-0.47,0.01l-0.85,0.61l-0.31,-0.25l-0.05,-0.51l1.1,-1.89l-0.43,-1.05l1.27,-0.71l0.95,-2.47l1.1,-0.34l0.71,-1.22l0.94,0.04l0.21,-0.77l-0.63,-1.58l0.35,-1.25l1.53,0.11l1.21,-0.64l0.49,0.11l2.74,-0.98l0.46,-0.53l0.2,-1.15l2.42,-2.25l0.73,-0.4l2.41,0.15l1.36,-0.95l0.13,-0.65l-1.09,-1.27l-0.14,-0.62l0.48,-0.52l-0.57,-1.32l0.48,-0.67l4.22,1.81l0.85,0.08l0.57,0.47l3.72,0.5l0.19,-0.85l-0.32,-0.48l0.91,-1.13l-0.16,-0.6l-0.44,-0.22l0.2,-0.81l-0.35,-1.34l1.7,-2.48l-0.18,-0.83l0.38,-0.8l-0.37,-0.83l-0.65,-0.49l0.17,-0.32l1.02,0.03l0.19,-0.38l-2.92,-2.29l-0.6,0.75l-1.1,-0.02l-1.93,1.13l-0.62,0.07l-0.61,-0.56l-0.98,0.16l-0.55,-0.78l-0.7,-0.16l-0.41,0.69l-0.93,0.02l-1.32,0.86l0.12,1.09l-0.52,0.39l-0.38,-0.29l-0.59,0.22l-0.38,0.73l-0.61,0.2l-0.68,-0.24l-2.03,0.2l-0.73,-0.28l-1.72,0.46l-0.14,0.64l-0.7,0.34l-0.66,-0.21l-0.34,-0.64l0.41,-0.4l-0.16,-0.35l-1.03,-0.11l-1.49,0.62l-0.49,-0.17l0.95,-1.62l-0.77,-1.65l0.23,-0.56l-0.5,-2.52l-0.69,-0.52l-0.87,0.19l-1.13,-0.56l-0.99,0.49l-0.74,-0.81l-0.83,-0.05l-0.54,-0.64l-1.04,0.12l-0.72,-0.39l0.89,-1.01l0.42,-2.01l0.75,-0.46l0.52,-0.88l1.49,-0.71l0.85,0.23l0.39,-0.21l0.85,-2.67l0.01,-1.11l0.99,-0.51l0.3,-0.73l1.28,-0.21l0.18,-0.51l1.35,-0.51l0.44,-0.7l0.71,-0.2l0.81,-1.51l1.89,-0.48l0.35,-0.54l0.02,-1.12l1.4,-0.36l0.91,-1.72l1.23,-0.16l0.23,-0.41l-1.81,-1.04l-0.28,-0.45l0.31,-0.77l-0.65,-0.46l-0.56,-1.26l-1.16,-0.19l-1.5,0.68l-2.59,0.31l-0.13,-0.49l-3.53,0.58l-1.15,-0.02L798.39,634.07z"
},
{
"id":"RU-KR",
"title":"Karelia",
"d":"M109.21,502.3l-0.98,0.47l0.57,0.28l0.19,0.85l0.5,0.3l-0.03,0.46l0.42,0.41l-1.36,1.48l0.79,0.57l0.44,-0.18l0.16,1.21l0.51,0.26l0.57,-0.21l0.11,1.08l1.46,0.19l-0.11,0.69l0.57,0.21l0.98,-0.7l0.37,0.25l0.32,-0.45l-0.3,-0.66l0.98,0.47l0.2,0.52l0.42,-0.02l0.42,0.54l0.3,0.51l-0.22,0.5l0.58,0.78l0.59,-0.52l1.35,1.34l-0.37,0.38l0,0.59l0.58,0.25l-0.12,0.93l0.24,0.34l1.26,0.04l0.06,0.3l1.01,0.27l0,0l-0.19,0.62l0.56,2.02l-1.83,2.62l-1.24,-0.35l-0.57,0.37l-1.35,-0.21l2.05,2.89l0.09,1.29l0.76,0.78l0.11,0.52l-0.59,0.78l0.24,0.25l0.88,-0.41l-0.09,0.58l-0.9,1.18l0.2,1.79l2.21,3.17l3.19,1.95l2.03,-0.36l0.71,0.27l0.82,1.29l0.1,2.65l-0.55,1.77l-0.51,0.03l0.07,0.62l0.64,0.79l0.97,-0.16l0.31,0.32l0.81,1.99l-0.07,0.79l0.73,0.58l0.04,1.09l-0.7,1.77l0.57,0.59l-0.04,0.32l-0.96,1.13l-0.07,2.11l0,0l-2.83,0.4l-0.63,-0.33l-0.42,-0.71l-0.42,0.03l-0.83,-0.6l-0.88,0.38l-0.49,0.86l-1.41,-0.54l-1.6,2.54l-5.68,3.19l0,0l0,0l0,0l0,0l0,0l-0.52,-0.55l-0.8,1.01l-0.28,-0.06l-0.74,-0.52l0.02,-1.59l-1.38,0.84l-2.53,-1.29l-2.13,1.46l-0.24,1.36l-1.89,-1.74l-0.58,0.27l-2.55,-0.32l-2.17,1.19l0.22,0.61l1.09,0.85l0.85,-0.49l0.93,0.42l-0.81,2.01l-0.26,0.28l-1.27,-0.84l-0.95,-0.11l0,0.65l-0.78,0.4l-1,1.09l-0.45,1.32l-0.63,0.37l-0.61,-0.14l-1.25,1.68l-1.08,-0.07l-18.44,-7.19l-0.85,-0.05l-1,-0.67l-1.18,0L71.15,558l-0.96,-0.4l-0.78,-0.95l0,0l1.29,-1.76l0.01,-0.53l0.96,-0.19l1.66,-2.76l1.21,-1.12l0.31,-0.92l1.7,-1.8l-0.02,-0.42l2.13,-2.71l0.33,-0.96l2.15,-1.7l-0.1,-0.34l1.57,-1.76l3.01,-7.19l-0.89,-1.88l-1.29,-1.26l-0.34,-1.79l-3.2,-2.91l-2,-0.85l-3.76,-4.71l1.94,-1.13l1.77,-3.13l0.41,-1.57l-0.59,-1.39l0.28,-0.38l-0.2,-0.58l-0.83,-0.37l-0.75,-0.99l-1.04,-0.36l-0.48,-0.75l0.11,-0.92l-0.42,-1.65l0.09,-0.56l0.87,-1l-0.71,-1.26l0.33,-0.82l-0.32,-0.26l-2.11,0.04l-0.48,-0.5l-0.37,-1.19l-0.26,-1.69l0.21,-1.19l0.78,-0.52l0.77,0.04l0.35,-0.28l-0.45,-0.57l0.49,-0.96l-0.13,-0.32l-1.58,-0.25l-0.35,-0.4l1.14,-1.42l-0.19,-2.27l0.97,-1.71l-1.03,-1.09l1.95,-1.08l0.85,0.42l0.02,-1.21l-0.38,-2.98l-1.19,-4.11l-1.72,-2.72l-0.56,-2.4l-1.27,-2.88l0,0l2.69,-0.63l2.43,0.17l2.91,-0.28l1,-0.36l2.85,0.2l2.05,-0.27l-0.07,0.35l1.64,0.1l0.13,1.88l1.02,0.45l0.8,2.07l3.13,0.11l0.22,-0.33l-0.2,-0.94l1.1,0.39l-1.19,-1.04l1.56,-0.17l0.29,-1.78l0.29,-0.21l1.91,0.26l0,0l2.42,0.92l-2.18,0.25l1.22,0.34l1.32,-0.38l0.48,0.37l-0.22,0.11l0.19,0.43l0.59,0.29l1.02,0.29l0.18,-0.57l0.42,0l-0.31,0.63l1.11,0.52l-1.59,0.39l1.32,0.98l-1.45,0.09l-3.3,1.31l1.73,-0.3l0.71,-0.55l0.55,-0.03l0.04,0.28l1.13,-0.33l0.21,0.14l-0.35,0.45l1.5,0.14l0.08,0.41l0.79,0.25l-0.14,0.56l0.53,-0.44l1.08,-0.05l0.54,0.65l-0.24,0.44l0.48,-0.1l-0.04,0.24l-0.01,-0.43l0.25,0.05l0.52,0.55l-0.13,0.21l0.34,-0.05l1.27,1.04l0.15,0.65l0.28,-0.12l0.19,0.26l0,0.48l0.66,0.4l0.11,0.38l-0.35,0.08l-0.11,0.63l0.3,0.12l-0.21,0.26l0.17,0.54l0.25,-0.45l0.75,0.2l0.17,0.42l-0.23,0.61l-0.54,0.15l0.72,0.29l-0.87,-0.2l-0.57,0.49l0.27,0.09l-0.16,0.34l0.29,0.54l-0.25,0.6l0.36,-0.28l0.35,0.35l-0.71,0.47l0.45,0.04l0.49,1.24l-0.16,0.26l-0.27,-0.29l0.01,1.08l-0.74,0.67l0.28,0.86l-0.56,0.25l-0.81,-0.2l0.32,0.61l-1.22,-0.12l0.58,0.7l-0.57,-0.26l-0.57,0.18l1.54,0.73l-0.35,0.35l0.2,1.12l0.46,-0.13l-0.06,0.64l0.47,-0.17l0.36,0.48l-0.33,0.04l0.69,0.72l-0.43,0.17l0.32,1.08l0.76,0.12l-0.28,0.61l0.24,0.11l-0.09,0.45l0.21,-0.18l-0.17,0.37l0.38,-0.44l-0.11,0.34l-0.95,0.63l0.66,0.13l0.38,0.92l0.09,-0.27l0.36,0.28l-0.09,0.37l0.59,0.69L109.21,502.3z"
},
{
"id":"RU-KK",
"title":"Khakass",
"d":"M494.72,637.57l0.89,1.02l0.45,-0.04l0.92,0.73l0.11,1.31l0.72,0.66l-0.21,0.6l0.79,0.1l0.38,1.07l1.05,-0.12l0.32,0.33l0.4,-0.81l0.86,-0.24l0.65,0.69l1.77,-1.04l1.61,-0.24l0.48,-0.58l0.24,1.06l1.48,0.62l0.34,1.1l-0.18,0.71l1.62,-0.42l0.22,0.91l0.9,-0.1l0.54,0.59l-0.43,2.04l2.18,1.71l0.66,2.62l1.52,2.67l0.01,1.1l-0.99,1.81l0.05,0.71l0.87,1.83l0.11,1.11l1.97,0.81l0.73,1.14l-0.04,0.76l-1.3,1.55l-1.06,0.62l-0.55,-0.02l0.15,0.28l-0.25,0.01l0,-0.3l-0.51,0.37l0.41,1.55l-0.08,0.94l-1.11,1.43l-1.46,1.03l-0.3,0.69l-0.69,0.28l-1.43,1.4l-1.78,3.45l0,0l-1.14,-0.1l-0.26,0.46l-0.59,0.22l-0.65,-0.34l-0.25,0.2l0.17,1.2l-0.63,0.62l-0.2,0.89l0.74,1.73l-0.3,0.34l-1,0.21l-1.11,1.55l-0.74,0.47l-1.3,-0.63l-1.5,0.6l-0.45,-0.19l0.21,-1.03l-1.27,0.32l-0.75,0.58l-0.94,0.1l0,0l-0.33,-0.08l-0.37,0.47l-0.14,1.17l-0.54,0.79l-1.36,0.51l-0.54,-0.41l0.02,-0.3l-1.16,-0.45l-0.74,-0.86l-0.95,-0.27l-0.24,-0.51l0.02,-0.59l0.71,-0.22l0.78,-1.33l-0.1,-0.55l-0.64,0.22l-0.67,-0.68l0.99,-2.63l1.58,-0.4l1.06,-1.33l0,0l0.66,-0.13l1.33,-0.94l-0.11,-1.06l1.69,-1.1l1.48,-1.49l-0.79,-0.84l0.13,-0.48l0.6,-0.36l0.27,-0.63l0.48,-0.1l-0.21,-0.64l-0.72,-0.33l-0.55,-1.02l-0.46,0.08l-0.25,-0.45l0.17,-0.84l0.84,-0.44l-0.06,-0.53l-0.68,-0.54l0.56,-0.27l-0.21,-0.51l-0.9,-1.36l-0.64,0.63l-0.11,-0.36l0.55,-1.59l-0.26,-0.87l0.89,-0.85l0.67,-1.53l1.39,-0.34l-0.47,-2.07l-0.91,-0.11l0.24,-1.56l0.99,-1.15l-0.28,-1.78l-0.21,-0.25l-1.19,0.56l-0.44,-0.28l-0.4,-1.01l-0.88,0.26l-0.5,0.93l-0.47,0.2l-1.28,-0.73l-0.25,-0.43l1.2,-0.62l0.34,-2.99l0.28,-0.72l0.69,-0.32l0.26,-0.93l-0.81,-0.73l-0.74,-1.43l-0.55,-3.19l0.02,-0.78l0.71,-0.34L494.72,637.57z"
},
{
"id":"RU-KL",
"title":"Kalmyk",
"d":"M172.73,729.17L172.61,727.83L172.89,726.91L175.07,725.61L175.06,724.77L175.79,724.41L176.86,724.95L177.54,724.92L178.34,723.99L178.58,723.48L177.16,722.76L177.34,721.93L177.88,721.28L179.21,721.65L179.01,722.72L179.26,723.01L180.31,722.53L180.67,722.93L181.23,722.89L181.69,722.64L181.42,722.11L181.6,721.75L182.25,721.74L183.69,722.38L184.2,722.13L184.2,722.13L185.99,723.56L186.65,723.3L187.32,723.53L187.22,725.27L189.16,727.7L191.74,729.78L193.72,727.6L194.83,727.93L194.57,728.37L193.65,728.79L192.82,729.85L195.19,734.23L195.75,734.44L196.26,735.49L197.04,735.57L198.05,737.01L197.77,737.91L196.56,738.44L196.15,739.09L196.08,740.2L194.68,740.29L193.34,741.57L194.35,742.16L195.17,742.22L195.48,742.66L195.52,743.74L195.83,743.96L197.83,743.52L198.06,743.94L196.34,747.6L195.41,748.89L197.57,748.94L198.85,748.45L200.28,748.7L199.76,749.63L200.43,750.23L200.43,750.23L199.85,753.65L198.88,752.52L199.26,753.83L198.87,754.01L199.01,754.48L198.45,755.29L198.03,755.14L197,756.83L196.51,756.24L195.98,756.82L195.87,756.47L195.43,756.36L195.43,756.36L194.37,756.79L192.96,756.2L191.76,755.19L187.77,754.53L186.91,754.8L186.91,754.8L185.95,753.39L185.12,752.8L181.47,751.11L180.91,750.5L177.75,749.63L176.2,747.98L175,745.76L172.72,744.88L171.03,744.71L170.11,743.81L167.79,742.86L167.09,742.17L166.14,743.55L165.29,743.73L164.36,744.56L162.67,744.78L162.81,743.28L162.09,743.07L161.73,743.12L161.93,743.85L161.5,744.27L161.64,745.04L161.36,745.16L160.06,744.51L158.33,744.39L158.33,744.39L158.46,743.98L157.9,742.9L158.16,742.53L158.76,742.31L159.47,742.75L160.2,742.21L160.11,741.26L160.8,740.89L161.67,741.11L162.02,740.77L161.18,739.54L160.85,738.71L161.02,738.54L163.55,739.61L164.33,740.41L165.49,740.94L167.41,740.41L170.53,742.91L172.11,742.88L173.12,740.41L173.63,740.83L173.67,741.58L174.43,741.18L174.59,740.91L174.06,739.64L174.37,738.81L173.54,738.51L175.44,735.92L175.88,735.95L176.69,735.2L176.75,733.8L177.24,732.3L177.33,729.44L176.52,728.95L176.72,728.54L176.13,728.44L175.88,729.52L174.64,730.01L174.35,731.17L173.99,731.15L173.4,730.86z"
},
{
"id":"RU-KHM",
"title":"Khanty-Mansiy",
"d":"M304.17,486.38L305.88,488.09L306.85,490.11L307.01,491.57L308.68,492.92L310,493.48L309.59,498.73L309.05,500.02L309.99,502.27L309.35,503.9L307.75,505.01L307.97,505.88L310.08,507.27L311.38,506.6L314.01,507.8L314.54,509.8L315.8,510.91L317.09,510.62L318.8,509.24L321.57,509.26L322.24,508.69L323,508.87L324.57,508.09L327.01,507.77L329.24,506.91L333.69,506.38L335.29,507.66L338.32,506.71L338.83,507.13L339.27,508.27L338.43,510.87L338.71,511.75L339.4,512.47L341.21,512.96L341.59,514.14L344.87,513.68L345.37,514.61L347.79,513.01L350.43,510.6L353.54,512.29L353.62,510.85L354.26,509.84L353.57,508.45L354.78,508.07L356.36,508.25L357.27,509.27L359.87,509.16L360.21,510.11L363.5,509.61L364.7,511.09L366.49,512.08L366.83,512.7L366.92,513.62L366.38,514.6L365.76,514.99L367.47,518.23L367.8,520.05L370.84,520.14L371.38,520.51L372.25,522.06L372.32,524.6L373.13,528.01L376.07,527.27L377.01,526.44L379.51,526.76L380.8,526.51L382.13,524.6L382.53,524.49L383.69,524.59L384.15,525.94L384.69,526.23L385.65,527.85L386.41,528.29L391,528.3L391.97,528.81L393.58,530.61L397.24,530.34L399,529.68L402.67,529.21L405.84,530.65L406.52,531.59L407.02,531.58L408.25,530.58L409.43,530.53L411.04,531.08L411.59,531.62L412.38,533.58L414.07,535.39L417.29,537.9L418.81,538.61L420.39,537.87L424.19,537.25L426.79,537.78L431.64,537.56L432.53,534.04L434.44,533.56L436.42,531.7L436.39,531.4L437.13,531.3L437.47,529.78L439.62,528.95L439.88,529L440.44,530.38L442.39,532.41L442.13,533.25L442.47,533.7L443.66,534.47L444.4,534.16L445.39,535.66L446.07,536.06L446.64,535.9L447.02,534.58L447.43,534.03L448.06,533.92L450.01,535.02L452.81,534.94L452.86,536.67L454.85,537.3L455.04,538.44L455.91,539.11L457.56,539.6L458.66,538.47L458.77,539.29L460.06,538.31L460.93,538.67L462.27,540.87L463.06,540.79L463.68,541.5L463.81,542.52L465.17,543.91L465.17,543.91L465.16,546.8L466.39,549.32L466.96,549.84L468.31,550.14L470.17,551.22L471.53,551.38L473.34,553.04L475.21,553.47L475.56,554.67L474.37,554.96L473.33,555.79L473.39,557.79L465.53,562.28L463.29,563.93L463.29,563.93L461.09,564.07L458.02,561.44L455.71,561.61L450.94,565.25L450.13,566.11L450.02,567.58L448.9,568.77L448.23,568.86L446.16,567.14L444.2,567.09L443.38,567.45L440.55,567.16L440.3,565.56L438.67,564.79L437.99,564.74L437.06,565.36L435.06,565.71L433.95,566.49L430.68,566.5L428.86,566.91L427.8,566.66L427.4,564.72L426.34,564.47L425.71,564.42L424.73,565.43L423.66,564.89L423.33,564.21L422.27,565.04L419.26,564.73L418.65,565.34L416.82,564.67L413.85,564.59L412.39,564.02L411.94,564.19L411.68,564.73L411.76,565.88L411.3,567L411.81,568.39L411.67,568.77L410.27,569.66L410.07,571.28L410.33,572.98L409.28,575.09L409.6,576.55L408.92,582.37L405.35,582.99L404.47,584.42L403.67,584.57L402.87,586.36L401.35,587.74L401.98,590.14L401.8,591.03L398.23,594.45L397.96,595.13L397.96,595.13L397,594.49L396.01,594.71L394.33,594.34L390.69,594.4L389.39,593L388.39,593.26L387.5,592.46L385.05,593.24L383.29,592.73L382.35,592.29L383.31,591.18L381.88,589.85L382.49,589.01L382.33,588.46L381.37,588.16L380.12,588.9L378.71,587.57L378.58,586.1L376.01,582.98L374.54,582.8L373.53,581.68L370.94,579.88L369.63,578.43L368.13,579.14L367.45,578.38L365.31,578.96L363.36,578.13L362.09,577.13L358.96,578.25L358.92,577.28L357.92,576.81L356.6,576.94L355.68,577.7L356.81,579.57L353.01,582.67L351.14,582.66L350.72,585.07L349.79,586.83L347.38,587.75L345.08,588.1L344.13,589.63L340.77,591.45L340.46,590.82L339.81,590.63L338.3,591.88L338.35,595L334.61,596.18L332.7,595.82L332.24,596.26L332.24,596.26L331.97,595.01L330.47,594.47L329.11,592.94L327.24,586.98L327.02,586.69L326.29,586.75L325.98,585.48L324.31,585.55L321.46,584.6L319.22,584.54L318.35,584.17L317.53,583.29L317,582.18L317.01,578.26L316.44,574.95L315.95,574.03L312.76,572.71L313.24,571.58L312.98,570.45L310.47,565.95L309.71,563.31L310.29,561.4L310.15,560.55L308.88,558.63L297.83,551.41L292.43,550.44L289.88,550.98L289.29,550.31L289.31,548.78L289.03,548.37L285.96,547.02L285.55,547.43L285.55,547.43L285.42,544.12L285.72,543.67L285.7,542.55L286.77,541.93L286.74,540.08L286.23,539.01L285.71,538.94L285.43,538.52L284.86,535.85L285.67,534.92L285.69,533.62L284.2,532L283.89,530.83L284.5,529.89L284.16,528.25L284.76,527.38L284.45,526.41L285,525.98L284.88,525.17L285.58,522.14L285.87,519.29L285.63,518.18L286.07,517.9L286.51,516.42L287.62,515.64L287.88,514.62L288.65,513.85L288.24,512.69L287.08,512.65L286.8,511.9L286.78,507.83L285.77,506.74L286.59,505.56L287.07,504.09L287.56,503.85L286.74,502.92L286.8,501.79L287.65,501.54L287.81,500.55L288.82,500.2L288.93,499.69L289.67,499.59L289.65,498.21L290.76,497.21L292.7,497.97L292.84,498.76L293.49,499.09L293.67,500.06L294.87,499.32L295.04,498.34L297.12,497.13L297.43,496L298.18,495.68L299.23,494.45L298.9,492.97L299.06,492.28L301.04,488.95L301.81,488.63L301.86,488.23L303.03,487.01z"
},
{
"id":"RU-KGD",
"title":"Kaliningrad",
"d":"M1.68,647.37l0.04,0.38l-1.71,1.85L1.68,647.37zM12.52,639.26l0.81,1.24l1.07,0.08l0.71,0.75l1.11,0.54l0.96,-0.03l0.23,0.73l1.05,-0.47l1.87,0.18l0.72,-0.31l0.58,1.26l0.17,-0.22l0.57,0.86l0.68,0.25l0.22,1.41l-1.06,0.8l0.09,1.05l-0.47,0.59l0.1,1.61l0.62,1.18l-9.44,0.52l-12.04,-1.42l1.06,-0.77l0.36,-0.96l0.72,0.27l1.7,-1.33l0.47,-0.04l-0.2,-0.34l-1.17,-0.01l-0.83,0.54l-0.3,-0.91l-0.45,-0.03l-0.25,0.33l0.13,0.74l-0.67,-0.1l0.67,-1.48l-0.24,-1.6l0.35,-0.81l1.12,0.21l0.99,-0.24l0.64,0.32l0.98,-0.38l1.3,-1.1l1.95,-2.77l0.34,0.15l-0.6,0.5l-0.38,0.93l-2.33,2.47l1.31,0.28l0.44,-0.21l0.65,0.58l1.59,0.09l1.12,-0.73l-0.49,-3.17l0.55,0.13l0.15,-0.64L12.52,639.26z"
},
{
"id":"RU-KO",
"title":"Komi",
"d":"M210.01,479.24L228.82,467.22L228.67,464.9L229.46,464.82L233.21,461.79L250.63,463.32L260.5,463.6L298.5,463.16L299.3,463.43L300.49,462.7L301.61,462.88L302.47,461.35L310.5,455.73L310.67,453.21L311.85,450.63L313.64,448.82L314.78,448.48L316.29,449.2L316.21,448.22L317.99,446.07L317.6,443.95L321.13,441.9L321.41,441.11L322.45,440.7L322.26,438.02L323.56,436.9L324.91,436.88L325.68,436.54L326.86,437.26L327.52,437.31L328.72,436.58L328.72,436.58L328.71,437.46L327.63,439L327.97,444.96L329.36,446.26L330.55,446.17L331.56,445.56L332.91,445.48L333.33,446.43L333.22,447.27L332.59,448.14L333.87,449.26L334.32,450.73L333.87,451.19L332.28,450.78L331.79,451.04L331.15,452.15L332.86,452.79L333.49,454L333.39,454.82L332.74,455.62L330.62,456.5L329.43,458.28L327.52,459.68L326.56,461.41L325.63,461.92L326.09,465L324.4,466.45L323.51,466.48L322.38,467.02L322.11,468.15L320.7,468.85L320.12,469.7L318.24,469.69L316.7,471.61L315.27,472.64L313.72,473.07L313.13,474.85L312.62,475.43L313.22,477.11L312.5,476.77L311.36,477.88L311.01,479.2L310.47,479.66L310.26,480.45L309.71,480.77L310.15,481.78L309.39,482.74L309.29,483.69L304.17,486.38L304.17,486.38L303.03,487.01L301.86,488.23L301.81,488.63L301.04,488.95L299.06,492.28L298.9,492.97L299.23,494.45L298.18,495.68L297.43,496L297.12,497.13L295.04,498.34L294.87,499.32L293.67,500.06L293.49,499.09L292.84,498.76L292.7,497.97L290.76,497.21L289.65,498.21L289.67,499.59L288.93,499.69L288.82,500.2L287.81,500.55L287.65,501.54L286.8,501.79L286.74,502.92L287.56,503.85L287.07,504.09L286.59,505.56L285.77,506.74L286.78,507.83L286.8,511.9L287.08,512.65L288.24,512.69L288.65,513.85L287.88,514.62L287.62,515.64L286.51,516.42L286.07,517.9L285.63,518.18L285.87,519.29L285.58,522.14L284.88,525.17L285,525.98L284.45,526.41L284.76,527.38L284.16,528.25L284.5,529.89L283.89,530.83L284.2,532L285.69,533.62L285.67,534.92L284.86,535.85L285.43,538.52L285.71,538.94L286.23,539.01L286.74,540.08L286.77,541.93L285.7,542.55L285.72,543.67L285.42,544.12L285.55,547.43L285.55,547.43L284.86,548.82L285.05,551.21L285.05,551.21L283.3,552.25L282.74,553.35L281.57,553.48L281.14,553.91L272.42,554.03L269.52,553.67L268.66,554.16L266.03,553.29L265.71,553.86L265.33,553.81L264.89,554.94L263.97,554.8L262.82,557.94L260.03,557.25L259.07,559.52L255.81,559.29L255.16,561.07L254.37,560.93L253.46,563.06L253.46,563.06L253.46,563.06L253.46,563.06L245.51,561.83L245.13,563.7L241.65,563.11L242.31,560.84L238.26,560.29L237.61,562.08L235.41,561.91L234.51,563.71L231.36,563.11L230.36,567.33L233.11,568.37L232.98,569.1L234.48,569.62L234.34,570.5L234.69,571.29L234.07,572.35L234.07,572.35L232.59,571.25L231.7,571.5L228.57,576.89L227.94,576.93L227.05,575.14L225.51,574.89L223.73,577.64L222.75,577.56L220.85,577.99L219.73,578.46L219.13,579.12L218.2,578.92L217.59,579.15L217.5,579.67L217.92,580.4L216.4,580.85L216.17,583L216.45,583.38L216.33,584.59L216.56,585.03L216.25,586.62L215.38,587.16L214.71,587.02L214.11,586.67L214.45,584.53L212.8,584.31L212.68,583.49L211.36,582.98L210.88,583.45L210.56,583.29L210.76,580.83L206.67,580.14L206.69,575.62L206.37,573.71L206.72,572.9L208.38,571.29L208.16,570.61L206.96,569.54L207.04,567.58L206.19,564.14L205.72,563.76L205.72,563.76L206.04,561.77L207.03,560.71L208.84,559.41L209.96,559.42L210.94,558.74L212.27,559L214.19,552.55L210.85,551.57L212.21,544.54L212.69,544.41L214.71,534.75L208.55,533.71L207.75,535.36L205.74,535.44L204.73,539.24L205.33,540.13L205.32,541.6L202.87,541.36L200.8,541.53L200.44,543.34L198.86,543.3L198.67,541.32L197.36,541.33L197.61,536.48L196.39,532.92L198.11,531.82L199.31,530.6L200.07,529.16L199.52,528.41L196.3,526.46L195.12,523.73L196.21,522.27L196.33,520.81L195.96,520L194.17,518.14L191.7,516.2L190.42,515.98L189.21,515.18L187.84,515.21L186.8,514.67L185.92,513.71L184.87,511.33L186.84,510.11L188.53,509.69L190.63,510.29L191.6,510.25L192.92,509.05L197.7,508.66L199.39,508.87L201.94,508.52L204,508.88L204.11,510.58L206.2,511.08L206.53,510.29L206.45,509.15L209.21,509.06L209.9,506.88L211.7,506.72L213.38,507.23L214.53,505L216.73,505.39L219.58,506.42L220.77,500.89L219.82,500.83L218.44,500.18L217.59,499.13L215.54,494.97L214.92,492.98L210.89,493.77L210.74,487.33L210.35,484.76L210.51,480.73z"
},
{
"id":"RU-KAM",
"title":"Kamchatka",
"d":"M1040.38,589.65l-0.3,1.93l-0.49,0.57l-1.1,-0.02l-1.46,0.85l-0.7,-0.06l-4.17,3.25l-0.71,1.71l-0.54,-1.43l1.28,-0.57l1.22,-2.83l0.07,-1.17l1.2,-1.57l-0.11,-0.36l2.7,-1.21l0.67,-0.9l1.41,-0.84l0.03,0.65l0.31,0.14l0.03,0.73L1040.38,589.65zM1109.09,549.65l-1.07,-0.52l-0.87,0.25l0.02,0.66l0.36,0.15l-1.81,1.86l-1.22,-1.36l-0.81,-0.04l-0.43,0.43l-0.08,2.48l-0.92,0.04l-0.38,0.39l0.04,0.79l-1.14,1.02l-0.6,0.11l-1.18,-1.19l-1.01,0.59l-0.16,0.42l1.39,0.88l0.23,0.82l-0.6,0.35l-0.91,-0.72l-0.76,-0.15l1.22,0.77l-1.04,0.88l-0.25,0.62l-0.93,-0.13l-0.8,-0.65l-0.4,0.16l0.19,0.71l0.52,0.43l-0.95,0.43l0.68,-0.12l-0.02,0.91l0.46,-0.38l0.12,0.4l-0.55,0.57l-0.85,0.03l-1.69,-1.33l-0.18,0.18l0.85,0.63l0.55,1.31l-0.56,0.37l-0.57,1.31l-0.46,-0.75l-0.26,0.14l0.05,0.61l-0.37,0.25l-0.68,-0.01l-0.23,-0.34l-0.52,0.17l-0.69,0.85l0.25,0.49l-0.2,0.39l-0.76,0.02l-0.91,0.72l0,0.72l-3.79,1.87l-0.86,1.2l-0.64,-0.07l0.08,0.52l-0.31,0.23l0.52,0.22l-0.05,0.6l-0.81,0.29l-0.41,0.5l-0.65,3.99l-0.78,0.53l-1.33,-0.55l0.18,-0.62l-1.38,-0.79l-0.72,-2.42l-0.6,-0.4l-0.34,-1.89l-2.29,-1.7l-2.27,-0.66l-2.27,-0.12l-0.52,0.33l-1.18,-0.74l-1.28,-0.06l-2.18,0.58l-1.44,0.83l-0.61,-0.38l-0.13,0.88l-0.3,-0.17l-0.77,0.58l-1.34,0.37l-1.58,1.07l-0.71,-0.3l-0.42,-0.6l0.16,1.27l-0.69,0.2l-0.63,0.99l-0.47,0.08l0.22,0.13l-0.83,1.6l-2.29,2.6l-0.87,1.6l-1.37,0.17l-0.13,-0.22l0.64,-2.34l0.17,-2.08l0.57,-0.42l0.17,-0.55l-0.42,-2.5l0.96,-0.67l-0.1,-0.71l-0.72,-0.12l-1.17,0.62l-0.7,0.97l-1.23,0.61l-0.56,0.73l-2.66,1.4l-1.15,1.19l-0.42,-0.35l-0.94,0.18l0.08,0.56l0.53,-0.39l0.43,0.1l-0.2,0.69l0.6,0.6l-0.41,0.3l-0.51,1.51l-0.97,0.38l-0.82,0.79l-0.42,-0.51l-0.14,-1.61l-0.43,-1l-0.67,-0.29l-0.35,-0.7l-0.89,-0.55l-0.9,0.5l0.12,1.14l-0.92,0.4l-0.58,0.72l0.01,0.38l0.56,0.48l-0.94,-0.13l-0.13,-0.44l1.23,-1.25l-0.59,0.07l-0.78,-0.63l-1.23,0.26l-0.41,0.36l-0.77,1.64l-0.3,-0.31l-1.04,-0.08l-1.01,2l0.25,1.84l-0.4,0.4l-0.95,0.18l-0.26,0.66l0.1,0.67l0.93,1.19l0,1.61l-1.84,0.46l0.1,1.01l1.01,0.6l0.15,0.77l-1.56,-0.96l-0.9,0.36l0.73,1.66l0.44,0.17l-0.21,0.48l-1.56,0.97l-0.22,0.75l-1.34,0.84l-1.14,1.19l-2.38,4.64l-0.93,3.51l0.3,2.08l0.75,1.29l2.14,0.9l-0.62,1.53l0.73,-0.29l0.58,-0.9l-0.24,-1.6l0.43,-0.77l1.01,-0.31l2.51,1.75l1.18,0.03l0.77,1.24l-0.67,0.82l-0.03,1.01l-0.57,0.26l-0.35,1.14l-1.36,0.67l-0.79,0.91l-0.21,1.58l0.62,2.73l-0.55,3.46l1.09,1.08l-0.84,-0.38l0.8,0.4l1.06,-0.67l0.42,0.21l0.77,-0.19l-0.03,0.37l0.39,0.3l-0.36,0.92l0.27,0.64l-0.17,1.7l0.75,1.44l0.06,1.82l-1.31,0.65l-1.12,1.65l-1.5,-0.76l-1.29,-2.05l0.55,-0.57l0.23,-0.94l1.44,-0.44l0,-0.44l0.94,-0.56l0.25,-0.8l-0.27,-0.17l-0.49,-0.17l-0.23,0.26l-0.45,1.3l-1.44,-0.84l-1,0.82l-1.11,0.35l-0.04,0.4l0.89,0.53l-0.03,0.37l0.33,-0.02l0.18,0.48l-2.84,1.43l-0.93,0.84l0.01,0.78l-2.34,5.92l-0.11,1.96l0.33,2.31l0.68,1.85l1.99,2.69l-0.36,0.42l0.24,0.83l-1,0.7l-2.17,2.39l-1.54,-0.17l-1.39,0.41l-0.62,-0.52l0.01,-0.7l-0.52,-0.15l-2.2,0.48l-2.46,1.69l-1.42,1.63l-1.12,0.73l-0.95,1.38l-0.97,3.14l-0.04,2.21l0.69,0.97l0.07,1.15l-0.14,0.26l-0.66,-0.33l-0.1,-0.46l-0.41,0.34l0.49,0.29l0.03,0.99l0.53,0.23l-0.05,0.69l0.44,0l-0.51,0.85l0.32,0.55l0.1,-0.49l0.39,-0.12l-0.14,0.4l0.46,1l-0.18,0.55l-2.09,-1.27l0.77,-0.79l-0.27,-0.07l-0.69,0.67l-1.01,-0.38l-0.75,0.31l-0.57,0.89l-0.42,-0.21l-1.71,0.71l-1.47,1.12l-1.33,1.56l-0.14,-1.1l-0.52,-0.86l-0.56,-0.12l-0.82,0.52l-0.06,0.45l0.42,0.19l-0.4,0.16l0.15,0.68l0.85,0.03l-0.11,-0.26l0.69,-0.07l-0.01,0.54l-0.28,0.06l0.38,0.28l-0.58,0.79l-0.51,-0.21l-0.08,0.24l0.05,0.42l0.82,0.51l-0.48,0.5l0.11,0.29l-0.32,0.13l-0.83,-0.41l0.16,0.59l0.81,0.81l-0.22,0.37l0.21,0.23l-0.92,0.85l0.78,-0.34l0.38,0.23l-0.12,0.6l-0.43,0.25l0.46,0.12l0.07,0.33l-1.17,0.92l0.14,0.64l-0.27,0.51l-0.18,-0.17l-0.33,0.27l0.16,0.58l-0.42,0.7l0.04,0.55l-1.21,1.78l-0.55,0.28l-0.86,1.8l-1,0.86l-1.47,0.59l-0.89,1.77l-0.48,0.01l-0.84,1.41l-1.2,0.81l-3.08,3.21l0.79,-1.41l-0.08,-0.94l-0.4,-0.13l0.09,-1.22l-1.2,-1.01l-0.45,-2.7l0.12,-3.46l-0.33,-4.18l-2.23,-7.88l-1.03,-8.78l-1.88,-10.18l-1.32,-10.13l0.7,-9.22l0.68,-1.76l1.77,-7.51l0.91,-1.63l0.48,-0.27l-0.76,0.95l0.86,-0.48l0.17,-0.8l1.79,-1.31l0.49,-0.9l0.06,-0.99l0.85,0.54l0.46,-0.15v-0.5l1.81,-3.8l0.12,-1.31l-0.3,-1.43l-0.62,-1.35l-0.71,-0.29l0.54,-0.99l0.39,-0.03l0.71,-0.77l0.35,0.77l0.88,0.36l0.92,0.1l0.97,-0.33l0.66,-0.48l0.4,-0.94l-0.09,-0.5l0.64,-0.57l0.09,-0.57l2.31,0.5v-0.27l0.93,0l1.38,-0.95l2.47,-2.6l2.95,-2.26l0.8,-1.38l2.47,-2.71l0.73,-1.53l0.32,0.08l0.3,-0.37l0.28,-1.23l-0.3,-0.44l1.05,-2.14l0.97,-0.8l1.41,-1.95l0.83,-0.17l0.75,-0.8l0.56,-2.22l2.76,-0.9l0.45,-1.17l1.21,-0.81l1.12,-1.27l1.66,-2.73l1.98,-1.15l1.08,-1.24l0.17,-1.23l-0.38,-0.17l0.44,-1.68l0.6,-0.17l0.4,-0.75l0.05,0.32l0.49,-0.27l0.3,-0.58l1.47,-0.29l0.75,-0.92l1.35,0.03l0.67,-0.66l0.76,-1.57l0.7,-0.3l0.88,0.36l-0.02,-0.38l0.47,-0.41l1.04,0.09l-0.02,0.65l0.57,-0.88l1.61,-0.8l1.07,0.5l-0.59,-0.28l0.53,-0.98l-1.99,-1.27l0.13,-0.37l0.71,-0.33l0.05,-0.81l0.35,-0.43l1.97,-1.38l0.59,-1.69l-0.75,-1.36l-0.71,-0.09l-0.39,0.4l-0.17,-0.76l0.72,-1.52l0.15,-1.22l1.34,-0.53l0.17,-1.8l-0.23,-0.61l0.36,-0.77l-0.18,-1.4l0.33,-0.55l-0.24,-1.14l0.37,-0.57l0.2,-2.16l2.03,-1.32l0.62,-1.29l1.45,-0.21l0.97,0.49l1.86,0.21l-0.27,-0.51l0.85,-0.35l0.18,-0.37l-0.96,0.04l-2.06,-1.21l-0.28,0.2l-1.17,-1.91l-1.22,-0.23l-1.18,0.49l-1.68,0.14l-0.88,1.1l-0.97,-0.38l-3.51,1.19l-0.35,1.24l-0.87,0.54l0.65,-0.14l0.18,0.64l0.97,0.68l-0.96,0.28l-0.05,0.47l-1.22,0.97l0.53,1.45l-0.23,0.81l0.59,0.23l-0.92,1.46l-0.04,0.98l-0.59,1.41l0.67,0.72l1.9,0.78l-0.03,0.68l-0.81,0.31l0.02,0.56l-0.3,-0.36l-0.51,0.19l-0.27,0.54l0.31,0.48l-0.58,0.51l-0.53,-0.98l-0.8,-0.35l0.63,-0.64l-0.72,-1.01l-1.5,0.74l0.11,0.55l0.78,0.05l0.11,0.48l-2.36,-1.19l0,0l0.21,-0.96l-0.74,-0.75l-0.63,-1.58l0.42,-0.4l0.53,0.09l0.95,-1.13l-0.36,-1.06l-1.64,-0.34l-0.51,-0.52l0.16,-0.61l2.22,-0.71l1.6,-1.07l0.02,-1.83l0.31,-0.9l-0.85,-1.7l0.89,-0.81l0.17,-0.7l-1.68,-0.74l0.54,-0.78l-1.64,-1.58l-1.04,-0.27l-0.07,-0.9l0.5,-2.15l0.48,-0.6l0.6,0.28l0.72,-0.2l0.67,-0.99l0.88,-0.4l0.06,-0.37l-0.61,-0.6l0.35,-0.78l-0.35,-1.33l1.11,-0.38l1.21,-1.73l-0.07,-1.25l-0.45,-0.81l-0.76,-0.32l-0.04,-0.69l-0.7,-0.56l0.69,-1.71l0.61,-0.52l-0.1,-2.04l-0.82,-1.36l0.18,-0.8l0.87,-0.62l1.58,-0.21l0.58,-0.49l-0.38,-0.49l0.11,-0.45l1.86,-1.36l0.02,-0.53l-0.69,-0.79l0.01,-0.72l-1.28,-1.33l-0.05,-2.13l0,0l-0.04,-0.67l-0.54,-0.55l0.04,-0.59l0.36,-0.27l0.77,0.14l1.56,-2.14l0.44,0.38l0.86,0.08l0.58,0.54l1.23,-0.05l0.66,-0.58l0.94,0.01l2.85,2.1l0.86,0.01l1.2,2l0.58,-0.44l-0.34,-1.42l0.32,-0.59l1.15,-0.39l0.66,0.25l0.58,1.26l2.64,0.15l0.85,2.08l-0.27,0.98l0.51,0.31l0.79,-0.17l0.74,-1.06l2.09,0.58l1.18,1.33l1.18,-0.37l0.89,0.16l1.16,-0.48l0.74,-1.08l0.49,-0.16l1.1,1.99l0.74,0.81l1.14,0.58l0.1,1.61l0.48,0.21l1.01,-0.34l0.13,0.84l0.66,0.22l1.12,-0.29l0.7,-0.65l0.39,0.27l1.37,-0.33l0.26,1.35l0.48,0.68l1.41,0.32l0.55,2.82l1.03,1.23l1.74,0.17l0.68,0.35l-0.07,0.94l1.03,0.63l0.81,3.08l-0.48,0.68l0.08,0.4l-0.76,0.64l-1.23,0.31l-1.23,1.64l-0.97,0.37l-0.32,0.89l-0.58,0.4l0.01,1.12l-0.88,1l-0.9,0.19l-0.25,0.53l-0.69,0.27l-0.08,0.7l1.87,1.08l0.48,0.74l1.26,0.52l1.12,-0.27l3.36,2.48l0.85,1.49l0.66,-0.03l0.62,0.6l0.77,0.06l0.29,0.84l-0.21,1.14l0.73,0.76l-0.18,0.63l0.56,0.65l0.28,1.53l0.43,0.37l0.95,-0.83l3.42,1.23l0.21,-0.53l1.24,-0.19l0.03,-0.6l0.68,-0.09l0.24,-0.69l0.42,-0.21l0.24,0.17l-0.1,0.95l0.77,-0.56l0.25,0.07l-0.15,0.72l3.22,-1.14l0.5,-0.89l1.36,-0.74l0.86,0.36l0.35,0.65l1.17,-0.05l0.43,-0.43l0.96,-0.21l1.34,0.52l0.84,0.73l2.23,-1.48l4.25,-1.44l0.78,0.25l0.34,0.67l0.91,0.07l0.63,0.49l0.36,1.17l-1.2,1.4l0.75,0.44l0.15,1.85l0.49,0.36l0.85,-0.21l0.3,1.28l0.58,0.48l0.17,0.95l0.51,0.45l-0.09,0.72l0,0L1109.09,549.65zM1054.27,646.89l-1.32,-1.36l0.13,-0.52l-0.66,0.08l-0.19,-0.31l-0.06,0.28l-0.63,-1.08l-0.79,-0.53l-1.42,-3.4l-1.61,-0.71l1.61,-0.99l1.06,0.53l0.91,-0.1l0.31,0.36l-0.42,0.44l0.03,1.12l1.41,2.67l1.08,0.62l0.36,0.6L1054.27,646.89z"
},
{
"id":"RU-KRS",
"title":"Kursk",
"d":"M109.8,674.61L111.14,674.36L111.46,673.89L112.53,674.26L112.6,673.63L113.27,673.99L113.42,673.39L113.92,673.56L114.34,675.48L114.66,675.66L119.33,674.35L119.74,674.47L120.75,676.1L121.69,676.25L121.95,676.71L122.68,676.76L123.71,677.54L125.84,677.92L127.35,679.52L127.66,679.42L128.02,678.56L128.67,678.65L129.14,679.23L129.7,678.33L130,678.4L130,678.4L130.51,679.51L131.66,680.01L132.77,679.71L133.43,679.87L134.07,679.47L134.07,679.47L135.14,680.17L135.44,680.92L135.29,681.74L136.26,682.25L135.55,682.94L134.98,682.55L133.15,683.01L134.26,685.03L134.54,686.42L134.28,687.3L134.28,687.3L131.88,685.62L131.12,685.68L130.15,686.34L129.06,686.07L127.56,686.17L127.09,686.54L125.6,686.87L124.88,688.02L123.07,688.33L121.67,689.51L119.78,689.1L119.12,688.63L118.17,688.98L117.57,688.32L116.94,689.03L117.38,689.27L117.21,689.79L116.66,689.93L116.18,690.75L115.56,690.46L114.96,690.92L113.96,691.09L113.61,690.41L112.93,690.26L112.93,690.26L113.16,689.87L112.52,689.51L111.52,689.82L110.92,687.94L109.95,687.79L108.76,688.47L107.88,688.34L107.65,687.66L105.92,687.44L105.38,687.84L104.89,687.52L105.41,686.33L104.55,685.85L105.23,684.44L103.61,682.89L105.98,682.16L105.95,680.93L105.3,680.48L105.3,680.48L105.92,679.72L105.09,679.44L105.27,678.47L106.16,677.79L107.6,677.84L107.87,677.07L107.57,676.4L107.94,676.14L108.51,676.47L108.77,676.32z"
},
{
"id":"RU-KOS",
"title":"Kostroma",
"d":"M197.05,581.75L196.67,585.26L198.17,585.51L198.01,586.5L198.32,587L198.06,587.18L198.52,588.14L199.22,588.47L199.46,587.96L199.63,588.82L200.33,589.88L200.61,591.58L198.51,591.37L198.28,591.52L198.67,592.08L198.33,592.39L198.76,593.06L197.89,593.55L197.32,593.39L196.35,594.34L196.54,595.35L195.68,595.54L195.38,595.34L194.96,595.73L194.07,595.89L193.89,595.68L193.23,597.1L193.44,598.12L192.11,598.74L192.66,599.07L192.14,599.73L192.48,600.78L192.21,601.28L191.78,601.32L191.36,602.21L191.8,602.9L191.8,602.9L188.55,603.52L188.03,603.38L187.81,603.76L187.5,603.72L187.25,604.69L186.84,605.05L186.35,605.03L185.17,603.52L184.29,603.76L183.43,602.96L181.02,603.08L180.69,603.55L180.95,605.77L180.57,606.16L180.73,606.83L180.23,607.17L180.08,608.1L179.04,607.98L177.45,610.46L176.56,610.51L175.22,611.47L172.71,611.37L172.71,611.37L172.58,610.74L172.13,610.34L170.86,610.07L170.11,610.39L169.18,611.57L168.98,608.96L168.45,609.91L168.74,611.27L168.53,611.74L167.76,612.24L166.64,612.13L165.86,611.34L166.48,610.74L166.1,609.7L166.35,608.47L165.51,608.18L165.22,608.88L164.01,609.05L163.72,608.78L163.09,609.05L162.88,609.55L162.04,609.7L161.65,609.45L161.28,609.75L160.12,609.06L159.99,608.58L157.58,607.85L157.82,609.41L157.51,611.1L154.79,611.95L154.27,611.69L154.27,612.24L153.81,612.84L153.4,612.82L153.4,613.24L152.57,612.75L151.21,612.93L150.97,613.31L150.26,613.14L149.56,613.56L149.56,613.56L149.07,612.96L148.95,610.97L149.38,610.72L149.23,610.14L149.81,609.99L149.73,609.35L150.05,609.66L150.23,609.25L150.74,609.52L150.95,609.12L150.35,608.03L150.98,606.78L150.43,605.42L151.5,604.61L151.42,603.15L152.58,602.31L152.28,601.57L152.79,601.29L153.46,600.18L154.18,599.94L154.7,599.26L153.96,598.31L153.77,597.2L152.97,596.81L152.97,596.81L153.32,596.47L153.59,596.62L153.41,596.02L154.12,595.3L154.65,595.2L155.2,594.15L154.43,593.24L154.87,592.37L155.17,592.54L155.15,591.78L154.67,591.44L155.24,590.89L155.23,590.51L155.58,590.3L155.87,591.1L156.26,590.49L157.87,589.42L159.03,589.05L160.02,589.21L160.36,588.61L160.59,588.87L160.99,588.75L161.11,587L160.12,586.33L160.85,584.34L161.86,584.61L162.07,585.89L162.62,586.59L163.06,586.1L164.75,585.73L165.26,586.97L165.61,586.98L166.32,588.24L166.7,588.11L166.73,587.38L167.03,587.64L168.06,587.34L168.03,587.01L168.65,586.55L169.34,587.16L169.54,586.99L169.78,587.37L170.08,587.25L170.04,586.52L171.18,586.04L171.44,587.73L172,587.44L171.9,587.03L173.22,586.38L173.24,587.19L173.94,587.12L174.75,587.54L175.88,587.17L176.04,587.78L176.88,587.98L176.92,588.39L178.3,588.06L181.81,588.61L182.3,587.65L183.84,587.69L184.17,587.18L186.68,587.57L186.87,587.17L187.38,587.6L188.54,587.7L189.41,585.68L189.98,585.78L190.26,585.29L191.81,585.11L192.05,583.74L191.74,583.32L192.07,581.98L193.58,581.86L193.72,582.29L194.32,582.17L194.73,581.66z"
},
{
"id":"RU-KU",
"title":"Kurgan",
"d":"M303.95,627.97L304.03,626.39L304.88,625.82L306.59,623.09L307.39,622.5L307.73,622.52L308.38,623.6L309.08,622.75L310.51,621.91L311.78,622.57L313.05,622.48L313.3,622.82L313.67,622.23L314.45,621.88L316.54,623.5L318.88,623.78L319.65,623.51L319.48,622.36L320.54,621.43L320.48,620.27L320.77,620L321.26,620.1L322.26,619.06L324.14,619.09L325.01,619.96L325.01,619.96L325.37,621.22L325.21,622.87L326.32,624.78L326.05,625.36L326.27,625.77L329.78,626.2L330.13,627.12L332.41,629.65L334.25,628.82L335.84,630.5L337.27,629.32L337.83,630.28L338.53,630.39L339.31,629.87L339.74,630.59L341.39,630.62L342.4,633.36L343.9,633.72L345.1,633.32L345.85,634.17L347.88,633.66L348.25,635.11L351.41,638.21L351.46,639.65L351.46,639.65L351.18,640.54L348.02,640.56L348.2,641.31L348.81,642.04L348.32,642.62L348.19,643.42L346.91,643.61L345.8,643.19L345.27,643.62L345.05,644.36L344.15,644.73L343.54,644.91L341.83,644.56L341.59,645.13L340.22,645.39L339.92,645.71L338.13,645.81L337.68,646.32L334.88,646.76L332.55,647.64L332.07,647.48L332.02,646.47L331.26,646.71L330.65,647.82L328.76,647.24L328.46,647.66L328.69,648.2L327.8,648.1L326.68,648.79L326.83,651.04L326.04,651.07L325.08,650.09L323.48,650.84L323.39,650.27L322.67,650.36L321.86,650.87L321.48,650.78L321.18,651.2L318.63,651.34L318.29,651.78L318.04,651.42L317.79,651.86L316.71,651.82L314.6,652.71L313.61,652.81L313.61,652.81L313.51,652.01L313.12,651.98L311.68,650.71L311.99,650.11L311.75,649.47L312.96,648.7L312.36,646.4L310.83,646.3L308.85,647.01L307.54,646.85L307.8,646.33L307.19,645.95L305.05,646.83L304.04,645.81L304.32,645.16L303.41,643.01L303.45,642.3L304.22,642.09L304.72,642.64L305.09,642.63L305.54,641.45L304.13,639L305.23,638.55L304.88,637.21L306.29,637.38L306.99,637.12L307.64,636.73L307.86,635.9L307.17,635.71L307.73,635.04L307.35,633.55L307.61,633.16L306.03,631.63L306.35,631.01L305.45,630.96L305.17,629.61z"
},
{
"id":"RU-KIR",
"title":"Kirov",
"d":"M196.68,563.69L197.15,561.9L197.59,561.34L197.51,560.76L198.94,560.99L199.63,560.54L202.58,561.34L202.96,561.7L203.05,563.29L205.72,563.76L205.72,563.76L206.19,564.14L207.04,567.58L206.96,569.54L208.16,570.61L208.38,571.29L206.72,572.9L206.37,573.71L206.69,575.62L206.67,580.14L210.76,580.83L210.56,583.29L210.88,583.45L211.36,582.98L212.68,583.49L212.8,584.31L214.45,584.53L214.11,586.67L214.71,587.02L215.38,587.16L216.25,586.62L216.56,585.03L216.33,584.59L216.45,583.38L216.17,583L216.4,580.85L217.92,580.4L217.5,579.67L217.59,579.15L218.2,578.92L219.13,579.12L219.73,578.46L220.85,577.99L222.75,577.56L223.73,577.64L225.51,574.89L227.05,575.14L227.94,576.93L228.57,576.89L231.7,571.5L232.59,571.25L234.07,572.35L234.07,572.35L235.34,573.07L241.67,574.11L241.83,573.1L242.38,572.86L242.38,572.86L243.59,574.62L243.98,576.05L243.18,580.31L243.18,580.31L242.28,580.44L242.03,582.45L240.69,585.21L241.97,588.06L242.84,588.07L243.97,588.72L244.68,588.54L245.11,588.91L244.52,590.17L244.84,592.2L245.61,593.21L245.61,593.21L245.61,593.21L245.61,593.21L244.58,593.78L244.38,594.4L244.69,594.93L244.47,595.37L244.75,597.31L244.75,597.31L243.99,597.41L243.63,597.83L243.15,597.64L242.58,597.97L242.33,597.66L242.03,597.77L241.95,598.29L240.85,598.21L240.01,596.58L238.57,597.11L238.41,598.15L238.06,598.51L235.13,598.28L233.38,597.53L232.74,597.55L231.53,598.12L230.56,599.27L229.65,601.62L230.8,602.72L230.85,603.59L231.66,604L231.21,604.91L231.48,607.39L231.08,608.56L230.29,609.36L230.18,609.97L229.21,610.55L229.24,611.1L228.6,611.33L228.06,611.07L226.98,611.2L226.4,611.62L225.66,613.41L227.77,618.15L228.66,619.08L228.56,619.72L227.8,620.37L227.46,621.58L226.24,621.53L225.99,622.22L226.21,623.09L225.95,623.69L227.04,624.75L227.22,625.48L228.41,626.3L227.71,627.12L228.43,627.66L227.91,628.39L227.91,628.39L227.67,628.98L227.17,629L226.36,628.36L225.83,628.53L225.08,628L224.31,626.85L224.58,625.68L224.33,624.86L223.88,624.37L223.36,624.65L223.56,625.5L222.38,625.15L221.71,623.83L221.83,623.26L220.4,621.16L219.81,621.78L219.26,621.48L218.84,621.89L218.2,621.63L218.2,621.63L218.68,619.96L218.38,619.07L217.76,618.68L217.33,618.85L215.92,618.44L216.21,617.46L215.91,616.96L216.01,616.5L215,615.94L213.87,616.21L213.17,616.76L212.47,616.45L211.86,614.78L211.84,614.01L212.29,613.26L212,612.8L210.89,613.12L210.72,613.84L211.08,614.5L210.5,614.99L210.36,615.86L210.07,616.02L209.28,615.71L209.55,614.99L209.09,614.67L208.16,615.11L207.28,614.74L206.53,615.58L206.08,615.02L205.37,615.02L205.12,615.84L204.58,616.04L204.55,616.71L203.81,616.96L202.47,617.05L201.62,616.25L199.94,618.24L199.82,619.05L198.95,618.75L197.29,619.27L197.46,618.67L197.05,618.13L194.45,617.83L194.45,617.83L194.71,615.66L194.32,615.04L195.01,614.46L194.2,613.11L194.07,611.7L194.6,610.57L194.99,610.32L196.35,610.58L197.97,609.53L199.11,610.3L199.55,610.1L200.09,609.04L200.48,606.17L201.75,604.72L198.89,603.75L196.79,603.51L192.77,603.25L191.91,603.6L191.8,602.9L191.8,602.9L191.36,602.21L191.78,601.32L192.21,601.28L192.48,600.78L192.14,599.73L192.66,599.07L192.11,598.74L193.44,598.12L193.23,597.1L193.89,595.68L194.07,595.89L194.96,595.73L195.38,595.34L195.68,595.54L196.54,595.35L196.35,594.34L197.32,593.39L197.89,593.55L198.76,593.06L198.33,592.39L198.67,592.08L198.28,591.52L198.51,591.37L200.61,591.58L200.33,589.88L199.63,588.82L199.46,587.96L199.22,588.47L198.52,588.14L198.06,587.18L198.32,587L198.01,586.5L198.17,585.51L196.67,585.26L197.05,581.75L197.05,581.75L197.16,580.27L196.94,579.75L195.35,579.1L196.19,576.68L196.47,573.96L195.05,575.37L194.22,575.59L191.99,574.48L191.36,572.75L193.72,572.36L194.38,572.53L194.74,572.22L195.37,568.97L196.66,567.61L196.18,565.17z"
},
{
"id":"RU-KYA",
"title":"Krasnoyarsk",
"d":"M473.33,298.63l0.66,-0.67l0.36,-1.85l1.25,-0.56l1.99,1.81l-0.49,1.11l-0.37,0.13l-0.23,-0.87l-0.93,-0.48l-0.33,0.31l0.69,0.32l0.21,0.45l-0.4,0.44l-0.56,-0.14l-0.69,0.69l-0.68,0.14l-0.05,-0.24l0.32,-0.05l-0.12,-0.47l-0.57,0.23L473.33,298.63zM525.5,134.23l-0.3,-0.22l0.28,-0.15L525.5,134.23zM505.98,69.99l-0.76,-0.96l-0.15,-1.28l0.62,-2.42l0.52,-0.63l3.27,-0.78l1.9,-0.06l0.67,-0.47l4.15,1.72l0.15,1.75l0.47,1.36l-1.22,1.79l-1.49,1.41l-1.85,0.37l-2.46,-0.21l-1.07,-0.71L505.98,69.99zM516.3,103.66l0.47,-0.13l0.43,-0.75l1.2,0.51l0.29,-0.86l1.57,0.61l-1,-0.96l0.21,-0.14l0.97,0.24l0.49,0.65l0.9,-0.53l1.19,0.6l1.33,-0.23l-0.69,-1.01l-2.91,-0.74l-2.01,-1.46l0.74,-0.69l1.63,-0.41l0.83,-0.9l2.1,-0.19l1.1,-0.76l0.04,-3.34l0.48,-3l2.78,-4.58l-0.11,-0.48l0.4,-1.08l-0.52,-0.42L527.73,84l0.29,1.33l-0.2,0.2l-0.8,0.03l-1.47,0.72l-0.4,-0.92l-0.51,1.09L524,86.7l-0.67,-0.08l-0.29,-1.14l0.85,-0.88l1,-1.89l-0.01,-1.5l2.18,-1.76l0.73,0.28l0.31,-0.19l-0.68,-1.39l0.03,-1.37l-0.34,-0.41l0.28,-0.34l0.94,-0.2l1.96,-1.86l1.37,0.55l0.2,-0.27l-0.33,-1.36l1.72,-1.04l1.02,-0.18l0.87,-1.22l0.83,-0.13l0.59,-0.51l0.57,0.11l2.58,-1.52l0.29,-0.74l2.94,-3.25l2.18,-0.19l-0.45,-0.54l-2.19,0.1l-0.87,-0.26l-0.18,-1.4l0.2,-0.21l3.31,-1.05l1.74,0.42l0.67,1l0.19,1.14l-0.86,2.18l1.7,-0.1l0.2,1.1l0.65,0.22l0.29,1.49l0.77,1.31l1.12,1.08l0.19,2.03l1.5,1.24l-0.36,1.44l0.8,2.14l0.77,0.18l1.48,1.27l0.41,1.15l1.86,1.48l0.03,0.63l3.02,0.53l-0.59,1.42l0.69,-0.07l0.43,0.82l-0.1,0.62l-0.73,0.74l0.88,0.4l0.24,1.76l-0.86,0.15l-0.73,0.96l-0.45,-0.28l-0.89,0.16l-0.3,0.83l-0.9,0.4l-0.38,-0.15l-0.08,-1.1l-0.46,0.54l-0.52,-0.35l0.1,0.96l-0.9,4.8l0.93,3.13l0.1,4.13l1.17,0.42l0.32,0.78l-0.01,0.69l-1.21,1.67l0.17,0.85l-1.26,0.06l-1.15,0.55l-1.35,-0.19l-3,0.56l-5.06,0.23l-1.94,1.52l-1.65,0.84l-1.16,0.19l-1.36,-0.31l-1.04,0.91l-0.72,-0.62l-1.62,3.12l-4.5,2.63l-3.83,-2.26l-2.83,-2.59l-3.1,-0.2l-1.36,-0.76l0.17,-0.38l0.79,-0.37l-0.09,-0.93l4.44,2.23l0.46,-0.35l-0.15,-0.64l-0.65,-0.65l-3.68,-2.02l-0.19,-0.74l-1.11,-0.82l2.28,-0.15l2.54,-0.71l1.56,0.43l1.88,1.43l0.65,-0.31l-0.79,-1.45l-2.19,-0.9l-0.87,0.07l-2.94,0.92l-3.34,0.22l-1.8,0.75l-0.28,-0.18l0.36,-0.71l-0.05,-0.68l-0.65,0.8l-1.4,0.43L516.3,103.66zM672.52,299.96l0.23,1.48l-0.18,1.15l-0.18,0.17l-0.13,-0.4l-1.58,3.91l-0.65,-0.12l-0.71,0.38l-1.15,2.68l-4.47,-1.38l-1.84,-2.27l-2.22,-0.71l-1.04,-1.19l0.17,-1.27l0.56,-0.59l0.97,-0.15l1.18,0.78l1.05,-0.83l-0.24,-0.37l0.36,-1.33l-0.53,-0.68l0.24,-2.39l4.93,0.92l3.27,0.23l1.31,0.87L672.52,299.96zM675.9,258.6l0.08,2.41l-0.32,1.83l-0.63,1.47l-0.5,2.74l-1.19,2.35l-0.8,-0.03l-0.39,-0.4l1.33,-1.87l0.19,-1.11l-2.03,-0.89l-1.21,-0.03l-1.15,0.48l1.1,-0.78l-0.03,-0.35l-0.53,-0.35l0.08,-0.35l-1.08,-0.57l-2.24,-2.4l-0.89,-0.54l-1.02,0.16l-0.63,-0.26l0.59,0.53l0.68,0.07l0.46,1.7l1.17,0.04l1.34,1.07l0.28,0.85l-0.21,0.51l-0.71,-0.03l-0.81,-0.71l-0.24,0.59l0.58,0.43l0.82,0.07l-0.04,0.72l0.54,0.64l0.01,0.48l-0.72,0.86l0.11,1.15l0.82,0.24l0.72,-0.53l0.05,-0.53l-0.36,-0.4l0.16,-0.54l1.79,-1.61l0.3,0.06l0.37,0.49l-0.13,0.98l0.25,0.31l-0.48,0.66l0.76,1.66l1.07,0.43l1.27,0.01l0.23,1.03l-0.08,1.7l-0.66,-0.14l-0.77,0.83l0.56,-0.26l0.63,0.3l-0.38,2.88l-0.91,2l-2.09,2.53l-1.46,2.53l-0.58,0.51l-0.16,-0.15l-0.14,0.86l-0.88,1.18l-1.24,0.65l-0.5,0.78l0.28,-0.85l-2.65,1.2l-0.44,-0.17l0.22,0.48l-1.27,2.86l-0.35,0.26l-0.38,-0.46l0.53,0.87l-0.92,1.21l-0.25,1.1l-1.66,-1.04l-1.04,0.2l-1.63,1.62l-1.46,2.28l-0.61,-0.15l-2.55,1.62l-1.36,-0.6l-1.15,0.23l1.45,0.25l0.15,1.14l-2.08,2.57l-0.63,0.09l0.91,-0.7l-0.56,-0.39l-1.47,1.65l-0.7,0.06l-0.12,0.57l-0.29,-0.73l-0.45,-0.08l-0.26,0.42l-0.45,-0.19l-0.08,0.31l-0.48,0l-0.41,0.65l-0.47,0.15l0.7,-0.02l0.39,-0.69l1.6,0.48l1.23,-0.77l0.15,1.15l-0.48,2.14l-2.5,3l-2.26,0.32l-0.91,0.58l-0.85,1.37l0.19,0.21l-1.14,1.16l-2.13,3.97l-0.62,-0.3l-0.25,-0.65l-0.77,0l0.69,0.2l0.13,1.55l-1.48,2.29l-1.2,0.1l-1.47,1.12l-1.57,-0.19l-0.79,0.32l-1.65,-0.39l-0.79,0.55l-1.55,-0.73l-1,0.27l-0.04,-0.28l-0.95,-0.21l-2.61,0.26l-0.52,-0.81l-0.74,0.4l-0.07,0.37l0.86,0.3l0.19,0.38l2.85,-0.26l2.76,1.57l0,1.83l-1.25,1.24l-0.13,2.17l-0.72,1.12l-0.82,0.25l-2.46,-0.4l-1.23,1.27l-0.68,2.49l-0.29,0.1l0.38,0.14l0.03,0.34l-0.98,0.96l-0.05,2.43l-1.01,1.32l-0.33,1.52l-2.69,2.21l-0.65,0.2l0.44,0.9l1.13,0.23l0.66,-0.31l2.18,-2.56l0.8,0.52l-0.41,-0.69l0.48,-1.26l1.63,-1.3l-0.14,-3.12l0.15,-0.58l0.73,-0.66l0.19,-0.79l0.68,0.04l1.21,0.88l1.27,0.35l2.5,-0.74l1.6,0.28l2.89,-0.11l0.54,-0.24l1.27,-1.49l0.63,-0.25l0.9,2.61l1.04,0.77l0.85,0.04l-0.73,-0.71l0.09,-2.65l1.18,-0.77l-0.45,-0.07l-0.5,0.36l-1.66,-0.38l-0.16,0.41l0.24,-0.95l4.8,-1.36l2.64,-1.26l0.23,-0.25l-0.48,-0.57l0.07,-1.12l0.53,1.16l0.81,0.59l0.64,-0.56l-0.34,-0.21l0.16,-0.59l1.92,0.43l0.54,-0.22l1.17,-1.29l0.79,-0.12l0.37,-1.12l-0.61,0.08l0.23,-0.62l0.61,0.07l1.43,-0.74l-0.18,-0.59l0.67,-0.71l0.82,0.14l1.68,-0.69l0.26,-0.44l0.35,0.13l0.06,-0.57l-0.37,-0.6l0.34,-1.16l-0.77,-0.1l-0.88,-0.65l-0.5,0.93l-1.25,0.61l-1.01,1.26l-1.26,-0.51l-2.32,0.29l-0.3,0.31l0.11,0.71l-0.58,-0.55l-0.69,-1.44l-0.29,-2.28l0.77,-0.3l1.43,-1.27l0.89,-3.09l2.62,-0.47l1.57,0.63l1.83,1.35l0.82,1.01l0.64,0.08l0.62,-0.68l0.09,-0.47l-0.34,-0.09l-0.02,-0.58l0.56,-1.24l1.24,-0.77l1.4,-0.08l0.53,1.12l-1.5,0.65l-0.75,-0.05l-0.44,0.42l0.55,2.46l0,0l-1.88,1.42l-0.57,0.85l-0.26,2.22l1.25,0.28l0.66,1.86l-0.4,0.32l-0.81,-0.54l-0.72,0.05l-1.54,4.51l-3.49,0.05l-0.44,0.78l2.97,1.49l0.15,1.38l-1.48,1.6l0.75,1.19l1.54,-0.6l1.31,0.37l0.29,0.61l-0.46,0.9l0.62,1.07l-0.08,1.03l-0.94,0.2l-0.52,0.98l1.21,0.24l-0.85,2.34l-0.31,1.98l0.44,3.79l0.65,-0.1l0.5,0.35l-0.18,1.21l1.42,0.34l0.74,0.89l-0.02,1.41l-0.72,0.77l-0.36,0.94l0.6,1.03l1.45,-0.07l0.58,0.85l1.08,-0.04l0.78,1l-0.3,2.31l0.79,0.23l0.47,0.94l1.37,0.48l0.31,4.5l-0.22,3.11l0.67,6.01l-0.2,2.19l0.24,0.75l1.5,0.73l1.26,1.71l1.12,0.15l0.63,0.45l-0.01,1.1l-1.03,0.24l-0.21,1.2l0.27,0.71l-0.35,0.94l-1.04,0.12l-0.37,1.08l-0.4,0.21l-0.57,-0.94l-0.46,-0.02l-1.25,1.76l-3.01,0.87l-0.71,1.32l-1.47,0.18l-2.11,1.58l-2.65,0.85l-0.87,1.07l-1.13,0.21l-0.88,0.73l-0.38,0.76l0.27,0.79l-0.51,0.4l-0.05,1.28l1.3,1l0.34,0.92l-4.83,0.78l-0.32,0.54l0.28,1l-0.38,1.2l-1.37,0.55l-0.12,1.21l0.51,0.59l-0.2,1.69l0.97,0.52l-0.05,0.55l-0.54,0.6l-0.19,1.96l-0.85,2.23l-1.31,0.46l-1.41,-0.24l-0.35,-0.52l0.06,-1.04l-0.59,-0.15l-3.69,0.24l-1.6,1.35l-0.62,1.57l-0.42,0.31l-1.31,-0.12l-2,0.69l-0.76,0.75l0,0l0,0l0,0l-2.53,1.53l0,0l0,0l0,0l-2.57,0.25l-1.26,-0.8l-1.03,0.83l-0.57,1.2l-0.68,0.39l-0.26,1.35l2.76,4.87l2.6,5.48l0.4,4.52l-0.19,9.14l-0.86,10.31l-0.11,4.91l-0.33,1.57l-0.7,0.72l-1.3,-0.45l-1.29,1.28l-1.52,0.22l-0.49,2.41l-0.61,0.37l-2.72,-0.02l-0.17,0.58l1.33,1.32l0.77,-0.42l0.81,0.17l0.15,0.92l1.4,-0.25l-0.02,0.95l-0.55,0.92l0.31,0.33l0.74,-0.2l0.14,0.92l0.58,0.72l-0.29,1.32l0.41,2.29l-0.92,1.68l-0.1,4.37l1.89,1.2l0.38,1.04l-0.05,6.4l1.42,0.82l1.14,1.72l1.1,-0.02l0.27,0.38l-1.23,0.91l-0.25,1.53l-0.6,-0.27l-0.82,0.12l-0.77,0.56l-0.61,1.4l0.58,1l-0.79,0l-0.75,1.23l-0.8,0.27l-0.25,0.76l-0.87,0.08l-0.29,0.5l0.07,0.84l0.55,0.47l0.01,0.74l0.71,0.59l-0.78,0.27l-0.44,-0.69L619,499.9l-0.24,0.81l0.25,0.67l-0.76,1.36l0.28,0.81l-0.25,0.41l-1.02,-0.04l0.31,1.34l-0.31,0.4l0.99,1.51l0.92,-0.95l0.96,0.27l0.11,0.77l-0.31,0.55l0.45,0.57l1.03,-0.47l1.88,-0.23l0.33,-0.36l-0.12,-0.65l0.61,-0.35l0.68,1.95l1.27,-0.1l0.41,0.89l1.89,0.17l0.23,1.49l1,0l0.53,-0.45l0.74,0.11l2.24,1.51l0.89,0l0.09,-0.61l0,0l1.11,0.51l0.45,1.5l0.95,1.11l-0.93,1.97l-0.57,-0.64l-2.83,0.13l-1.26,0.36l-0.28,1.11l-0.53,0.36l-1.12,-0.19l-1.06,-1.09l-0.79,0.97l-2.72,-1.47l-0.3,0.3l0.48,2.22l-0.66,1.7l-0.12,2.04l-0.9,1.24l0.31,0.89l1.25,1.69l-0.39,0.65l-0.74,0.4l-0.77,-0.56l-0.59,0.3l-0.28,1.01l0.64,0.72l-0.35,1.76l-0.51,0.37l-1.08,0.11l0.21,1.93l1.33,1.27l0.99,1.72l-0.33,0.83l0.5,0.7l1.83,0.53l-0.53,0.9l0.09,0.81l-1.94,2.07l-0.16,0.76l-0.62,0.78l0.05,0.5l0.45,0.4l-0.56,2.58l-3.38,3.25l0.44,1.94l-1.01,0.77l-1.36,0.02l-0.34,0.68l-2.19,1.69l-0.13,0.58l-2.36,1.07l-0.1,0.71l0.55,0.59l0.23,1.01l-2.17,1.22l-0.05,0.65l-0.77,0.35l-0.3,0.78l0.06,2.23l-0.83,0.42l0.05,0.66l0.58,0.16l0.25,0.56l-0.68,1.59l0.59,1.37l1.79,2.08l2.01,1.16l1.25,-0.17l0.54,0.6l0.68,-0.14l-0.14,2.86l0.34,0.79l-0.4,1.15l0.58,0.56l0.04,0.6l-3.12,-0.12l-0.65,1.32l-1.65,1.3l0.58,0.94l0.14,0.96l1.19,1.34l1.02,-0.02l0.11,1.1l-0.35,0.65l1.19,1.25l0.17,1.81l-0.47,0.49l-1.18,0.4l-2.42,2.27l-0.18,0.61l0.39,0.88l0.54,0.4l-1.57,1.38l-0.87,0.01l-0.46,0.36l-1.09,-0.22l0.08,-1.2l-0.61,-0.11l-0.11,-0.69l-1.01,-0.13l-1.07,0.52l-0.18,-2.08l-2.94,-0.83l-1.29,-1.6l-0.03,-0.73l-0.79,-0.97l0.03,-0.85l0.9,-0.01l-0.03,-0.44l-1.29,-0.17l-0.69,0.32l-0.95,-0.49l-0.81,0.8l-0.18,0.59l-0.99,-0.2l-1.53,0.75l-0.57,1.71l1.08,2.16l0.18,1.89l-0.46,0.84l-1.24,0.68l-1.3,1.76l-2.71,0.69l-0.59,0.54l-1.07,2.4l-0.92,0.2l-1.9,1.58l-0.09,0.58l0.59,0.37l-1.22,1.46l-0.02,0.8l-1.86,-0.1l0.43,1.39l-0.41,1.36l0.36,1.08l0.59,0.36l0.17,0.96l-0.32,0.33l-0.65,-0.16l-0.53,0.85l-0.47,-0.03l-0.34,-0.79l-1.48,-0.84l-0.17,-0.73l0.32,-0.45l-0.57,-0.6l0.26,-0.76l-0.55,-0.48l0.08,-0.53l-1.43,-0.3l-0.38,-0.34l-0.26,-1.14l0.55,-1.1l-0.81,-0.81l-0.92,0.39l-0.75,-0.39l-0.97,0.22l-0.26,1.1l-0.72,0.47l-0.46,2.1l-1.48,0.34l-0.66,-0.14l-0.51,0.62l-1.66,0.08l-0.44,-0.76l-6.09,-0.23l-4.15,10.01l1.99,1.07l-0.2,0.67l-0.83,0.45l-0.1,0.59l0.28,0.45l2.08,0.13l-0.31,2.76l0.97,0.14l0.13,0.29l-0.3,0.91l0.18,0.94l-2.53,0.33l0.12,2.19l-0.76,-0.06l-0.1,1.23l-0.82,0.83l-0.4,-0.48l-0.89,-0.12l-0.28,0.99l-0.92,0.11l-0.28,1.76l-1.31,1.21l0.11,1.25l-0.3,0.42l0.69,0.59l-0.14,2.28l0.67,1.2l-1.81,0.82l0.37,1.13l-0.62,2.48l0.52,0.58l0.09,0.89l-1.24,3.33l0.05,0.63l-3.16,-0.37l-0.87,1.59l-1.39,0.25l-0.68,0.9l-0.12,1.29l0.81,0.15l0.54,0.81l1.48,1.06l0.04,0.71l0.77,0.46l1.04,1.85l0.66,0.41l0.72,1.14l1.65,0.39l0,0l-0.23,0.94l-1.93,0.7l-1.3,-0.63l-0.18,0.64l-0.67,0.16l-0.43,0.62l-1.42,-0.38l-0.76,0.28l-0.25,-0.38l-2.44,1.35l-1.36,-0.76l-1.08,0.87l-0.07,-0.22l-2.16,0.25l-0.72,0.63l0.59,0.55l0,0.43l-0.55,0.42l-0.74,3.35l-1.56,0.19l-0.82,0.43l-1.06,2.39l-0.58,0.33l-0.05,0.88l-1.1,1.07l-0.02,1.22l-0.77,0.57l-0.3,1.51l-1.29,0.25l-0.65,0.46l-3.57,3.41l-1.3,-0.07l-1.84,0.71l-0.95,-0.22l-2.18,0.64l-0.73,-0.2l-0.72,-0.94l-1,0.26l-1.61,-0.66l-1.89,0.29l-0.42,-0.57l-0.56,-0.15l-1.35,0.58l-1.03,-2.09l-1.42,-1.21l0,0l1.78,-3.45l1.43,-1.4l0.69,-0.28l0.3,-0.69l1.46,-1.03l1.11,-1.43l0.08,-0.94l-0.41,-1.55l0.51,-0.37l0,0.3l0.25,-0.01l-0.15,-0.28l0.55,0.02l1.06,-0.62l1.3,-1.55l0.04,-0.76l-0.73,-1.14l-1.97,-0.81l-0.11,-1.11l-0.87,-1.83l-0.05,-0.71l0.99,-1.81l-0.01,-1.1l-1.52,-2.67l-0.66,-2.62l-2.18,-1.71l0.43,-2.04l-0.54,-0.59l-0.9,0.1l-0.22,-0.91l-1.62,0.42l0.18,-0.71l-0.34,-1.1l-1.48,-0.62l-0.24,-1.06l-0.48,0.58l-1.61,0.24l-1.77,1.04l-0.65,-0.69l-0.86,0.24l-0.4,0.81l-0.32,-0.33l-1.05,0.12l-0.38,-1.07l-0.79,-0.1l0.21,-0.6l-0.72,-0.66l-0.11,-1.31l-0.92,-0.73l-0.45,0.04l-0.89,-1.02l0,0l2.33,-2.89l1.67,-0.39l0.51,-0.7l1.14,-0.52l0.12,-0.93l-0.73,-0.34l-0.64,-1.73l0.06,-1l-1.01,-1.19l-0.31,-1.31l-1,-0.07l-0.4,-0.85l-1.12,0.02l-0.87,-1.32l0.12,-0.55l-0.83,-0.68l0.25,-0.75l0.66,-0.05l0.33,-0.34l0.1,-0.81l-0.52,-2.18l0,0l0.82,-1.93l-0.33,-0.72l-1.2,0.13l0.14,-0.54l1.14,-1.1l1.34,-3.07l1.51,-0.73l-0.3,-1.1l2.25,-0.72l0.16,-2.42l-0.13,-1.01l-0.83,-0.84l-0.64,-0.18l-1.52,0.25l-1.52,-0.72l-0.76,-0.95l-3.99,-0.84l-0.1,-0.94l-0.77,-1.26l-0.25,-3.58l2.77,-3.21l1.55,-2.38l2,-1.05l-0.13,-0.85l-1.37,-1.47l-0.12,-1.17l-0.19,-0.32l-1.05,0.05l-3.85,0.56l-1.24,-2.02l-1.51,-3.92l-2.42,-0.08l-0.14,-2.03l-0.33,-0.66l-0.82,-0.34l-4.56,-0.88l-3.27,0.23l-2.36,0.64l-6.44,0.17l-0.48,-1.55l0.57,-1.07l-0.01,-2.08l0.66,-0.58l0.57,-1.34l-3.07,-5.98l-0.84,-0.63l-0.19,-0.82l0,0l2.24,-1.66l7.86,-4.49l-0.06,-2l1.04,-0.83l1.19,-0.3l-0.35,-1.2l-1.87,-0.43l-1.81,-1.66l-1.35,-0.16l-1.87,-1.08l-1.35,-0.29l-0.57,-0.52l-1.23,-2.52l0.01,-2.9l0,0l0.51,-1.34l2.38,-2.8l0.3,-2.05l0.59,-1.4l1.69,-1.69l0.53,-1.33l1.12,-0.96l0.19,-1.3l0.4,-0.32l0.18,-0.79l-0.59,-1.5l0.38,-0.53l-0.16,-0.72l0.33,-1.79l-0.43,-0.26l-0.68,0.12l-0.79,-1.82l-1.4,-0.79l-0.21,-0.75l1.38,-1.43l0.3,-2.76l1.05,-0.59l1.32,-1.44l1.97,-1.45l0.03,-3.52l-0.54,-1.64l0.18,-0.62l-0.69,-1.48l0.74,-1.33l-0.77,-3.58l-0.68,-0.07l-0.2,-0.41l-0.91,-0.38l-1.5,1.08l-0.7,-0.12l-0.68,-0.8l-1.03,-0.36l0.6,-0.71l-0.18,-0.54l-2.59,0.49l-2.09,-0.21l-0.29,-0.43l0.48,-1.04l-0.79,-1.88l0.54,-1.19l1.71,-1.61l-0.76,-3.72l-0.96,-0.85l-1.68,-0.56l1.28,-0.76l-0.34,-0.81l-2.52,-1.74l-1.46,0.35l-0.88,-0.27l-0.44,-0.59l-0.24,-1.9l-0.97,-1.26l-0.24,-0.83l0.67,-0.7l0.02,-0.88l0.99,-0.7l-1.64,-3.33l-1.85,-2.23l-0.07,-0.81l0.79,-1.3l0.69,-0.55l0.27,-0.88l-0.81,-2.4l-1.15,-0.74l-0.13,-1.04l-6.36,-5.85l1.35,-1.61l-0.17,-2.06l0.58,-1.2l-0.05,-0.69l-1.99,-2.03l-0.3,-1.92l-1.01,-0.75l-1.21,-2.54l0.3,-0.34l0.71,0.03l1.29,-0.52l0.98,0.44l1.2,-0.4l0.1,-2.73l1.01,-1.23l0.23,-1.64l1.19,-0.85l0,0l0.15,-3.04l0,0l-0.43,-2.61l1.6,-1.08l-0.12,-1.1l-0.33,-0.99l-1.73,-1.75l-0.51,-2.69l-0.98,-1.88l0.79,-0.99l-0.5,-0.96l-1.43,-0.14l-2.34,-0.87l-0.14,-0.74l1.08,-1.51l0,-1.1l-2.04,-1.5l-0.51,0.86l0.15,1.25l-0.23,0.95l-0.61,0.64l-0.73,0.17l-0.96,-0.26l-1.69,1.04l-0.88,-0.08l-2.34,-1.8l-0.94,0.11l-1.87,-0.78l-2.2,0.19l-0.85,-0.47l-0.78,-1.37l-0.55,-0.12l-1.35,-4.51l-2.84,-0.62l0.25,-1.75l-0.84,-1.6l-0.26,-1.18l1.53,-1.51l1.41,-2.3l0.07,-1.44l0.32,-0.49l0.5,0.12l0.56,0.22l0.12,0.59l1.08,-2.11l3.55,-3.53l0.05,-0.71l0.86,-0.43l1.56,0.03l1.18,0.93l0.82,0.08l0.33,-0.57l-0.12,-0.42l-1.09,-1.25l1.19,-3.29l-1.25,-1.4l0.62,-2.19l-0.77,-1.65l-0.21,-2.8l-0.55,-1.04l-2.44,-0.75l-2.49,-1.21l-2.47,-3.4l-0.84,-0.07l-0.64,-0.57l-0.51,-2.33l0.17,-0.84l0.59,-0.26l0.23,-0.76l-0.14,-2.2l2.86,-0.08l1.36,-0.66l0.96,-1.44l0.59,-3.01l1.56,-0.52l0.2,-0.53l-0.45,-1.18l-2.28,-1.66l-1.4,-0.45l-0.71,-0.88l-2.16,0.37l-1.63,-0.25l-2.09,-1.57l-2.16,-2.24l0.12,-1.33l-1.36,-2.52l0,0l4.8,0.24l1.94,0.41l3.08,3.24l1.01,0.62l-0.2,0.6l0.58,-0.47l3.67,1.77l0.81,2.17l0.94,0.15l0.68,1.32l2.15,2.42l0.6,2.1l2.4,1.43l1.32,0.17l2.82,-0.43l3.35,-1.41l0.98,-0.11l0.66,0.02l0.57,0.85l1.47,0.28l0.53,0.74l0.07,0.71l-0.97,1.89l-1.38,0.86l0.17,2.83l-1.99,0.88l-3.44,2.52l0.59,4.14l-0.93,1.42l0.59,0.52l-0.15,0.77l-0.13,-0.42l-0.12,0.32l1.39,4.49l-1.1,1.28l-0.29,1.65l-0.96,0.92l0.54,1.34l-0.05,0.66l-0.58,1.1l-1.15,0.72l0.08,0.51l-0.5,0.51l0.45,-0.14l0.11,0.94l-0.88,1.83l0.35,0l0.66,-1.83l0.08,-1.84l0.66,-0.21l0.74,-1.29l-0.02,1.52l0.21,-0.03l0.03,0.73l0.54,0.37l0.08,0.74l-0.2,0.31l-0.08,-0.22l-1.18,-0.01l-0.35,0.27l1.19,-0.07l0.33,0.27l0.79,1.35l0.15,0.91l-0.76,0.41l-0.4,0.64l0.05,1.36l0.23,0.14l-0.1,-1.52l0.47,-0.64l0.65,-0.26l0.25,0.39l0.3,-0.62l1.48,0.54l2.39,2.55L454,404.9l-1.29,-0.17l-0.53,-0.54l0.05,0.32l0.49,0.37l1.35,0.19l1.3,0.75l0.4,0.92l1.6,1.79l0.65,1.78l2.45,0.06l-0.08,0.36l0.12,-0.59l0.7,0.02l1.54,3.2l0.81,0.43l0.88,-0.27l1,-0.95l-0.25,-0.4l-0.8,0.41l-0.34,-1.55l-2.06,-0.57l-1.1,-1.67l0.14,-0.16l0.37,0.47l-0.16,-0.44l-1.23,-0.54l-0.64,-0.81l-0.96,-1.8l-0.28,-1.28l-0.65,-0.72l-2.08,-0.62l0.25,-1.38l-1.4,-3.12l0.41,-0.97l0.02,0.25l1.14,0.45l0.91,-0.05l1.15,-0.71l0.41,0.6l-0.08,-0.7l0.42,-0.19l1.34,-2.2l-0.34,-0.93l0.28,-0.38l-0.45,0.12l0.42,-0.41l-0.06,-0.45l-0.58,-0.85l-1.15,-5.26l0.06,-0.83l-0.78,-2.75l-0.78,-1.15l-0.62,-0.13l-0.46,-1.3l0.59,0.31l0.18,-0.73l-0.81,-2.34l1.22,-1.35l0.78,-3.96l0.85,-0.53l0.49,-0.82l0.34,-1.36l-0.12,-0.82l-1.1,-1.71l-0.73,-0.61l0.28,-1.18l-0.94,-1.29l-0.91,-0.55l-2.71,-0.49l-0.31,-0.3l-0.4,0.24l-0.04,0.5l-1.31,-3.83l-1.81,-1.51l0.15,-0.28l0.52,0.37l0.87,-1.05l-0.38,-0.1l0.13,-0.35l-0.33,-0.16l-0.86,-2l-2.57,-1.33l0.37,-0.85l-0.59,0.61l-1.3,-0.25l-0.39,-0.38l-0.85,0.24l-0.24,-0.37l-1.4,0.03l-2.07,-1.53l-0.64,-0.15l-0.44,-0.58l-0.63,-1.61l0.14,-0.51l0.51,-0.23l-0.25,-0.79l0.77,-0.91l-0.42,-0.5l-0.84,0.53l-0.4,-0.27l-0.15,-1.41l0.08,-1.14l1.43,-1.61l-0.28,0.05l-0.22,-0.61l0.43,-2.51l-0.61,-1.98l0.1,-0.48l-0.83,-0.82l-1.31,-0.59l0.81,-0.34l-0.11,-0.94l-1.47,-0.47l-0.17,-0.71l-0.54,0.28l0.63,-0.53l1.4,0.15l-0.04,-0.54l0.61,0.44l0.96,-0.24l-0.81,-0.33l-0.29,-0.6l0.28,-0.08l-1.26,-1.1l-0.5,0.23l-0.71,-0.51l0.7,-1.59l0.42,0.27l0.45,-0.29l-0.17,-0.53l0.75,-0.36l0.62,-1.02l-0.6,-0.07l0.12,-0.67l0.32,-0.21l-0.18,-0.51l-0.51,0.2l-0.07,0.63l-0.21,-0.03l-0.1,-0.73l-0.41,-0.41l0.47,-0.66l-0.28,-0.39l1.65,-0.42l0.71,0.66l0.44,-0.03l-0.01,-0.51l1.31,-0.16l-0.09,-0.28l1.65,0.17l0.57,-0.27l0.06,-0.45l3.6,-0.85l3.17,-0.33l0.48,0.53l0.08,0.63l0.18,-0.31l-0.37,-0.87l7.67,0.17l6.61,-1.78l2.6,-1.18l1.3,0.29l1.11,0.92l1.61,0.14l1.32,-0.41l0.08,-1.46l1.18,-1.06l1.76,-0.08l1.28,-1.02l3.18,-0.59l0.3,0.34l1.3,-0.63l0.14,0.29l0.7,-0.1l0.36,0.47l1.15,0.42l0.8,-0.65l-0.32,0l-0.31,-1.62l-0.37,-0.8l-0.81,-0.43l-0.28,-1.07l1.15,-0.58l1.69,0.03l-0.05,-0.4l1.01,-0.41l-4.04,0.59l-0.54,-0.65l0.29,-0.54l-1.08,-0.57l0.57,-1.33l-0.76,-1.52l-0.5,-0.39l-1.31,-0.08l-0.81,-0.75l-1.14,0.15l-1.37,-0.62l-0.51,-0.81l0.06,-0.94l0.45,-0.83l0.96,-0.15l0.27,0.42l0.24,-0.28l0.96,1.91l0.18,-0.69l-0.34,-1.43l-1.52,-0.75l1.11,-0.19l0.09,-0.24l0.49,0.29l0.02,-0.54l0.38,-0.34l0.29,0.3l0.42,-0.57l0.67,-0.03l1.09,1.25l-0.33,0.7l0.55,-0.31l0.46,0.87l0.18,-0.54l1.16,0l-0.18,0.9l-1.59,1.43l0.81,0.4l0.16,-0.9l0.88,-0.49l-0.16,0.8l0.33,0.45l-0.35,0.72l0.3,0.15l0.4,-0.42l0.08,-0.94l-0.53,-1.35l0.17,-0.34l1.33,0.86l1.11,-0.13l0.02,-0.72l-0.52,-0.24l0.13,-1.17l-0.4,0.07l0.39,1.86l-0.41,0.24l-1.56,-1.39l0.47,-1.15l0.52,-0.21l-0.37,-0.29l0.02,-0.46l-0.69,1.43l-1.37,0.34l-0.57,-0.17l-0.04,-0.33l0.35,-0.2l-0.78,-0.16l0.2,-0.92l-0.31,0.16l-0.31,-0.74l-0.49,0.14l0.04,-0.54l1.37,-0.88l-1.64,0.1l-0.34,-0.26l0.07,-0.36l-0.99,-0.26l0.27,-0.77l-0.85,-0.13l-0.05,0.28l-0.64,-0.08l0.03,-0.26l-1.19,0.04l-0.2,-0.4l-0.29,0.51l-0.44,-0.19l-0.86,0.52l0.66,-0.76l-0.86,-0.57l0.96,-0.79l-0.46,-0.53l0.11,-0.51l0.87,-0.51l0.63,0.51l0.28,-1.32l0.35,0.15l0.2,-0.3l-0.9,-0.69l-0.16,-0.87l0.77,-0.09l0.34,1.06l0.55,-0.68l0.03,0.47l1.06,0.69l0.03,0.59l-0.77,-0.26l-0.34,0.35l0.49,0.43l0.34,1.04l0.49,-0.87l0.58,-0.12l0.3,0.3l-0.19,0.64l0.84,-0.52l-0.06,1.14l-0.5,0.46l0.98,-0.21l0.29,0.35l-0.39,0.37l0.02,0.85l0.72,-0.44l1.25,0.78l-0.67,-1.1l0.18,-0.72l0.41,-0.25l-0.25,-0.23l-0.9,0.13l-0.3,-0.67l0.51,-0.48l-0.23,-0.21l0.5,-0.12l-0.22,-0.27l0.24,-0.36l0.42,0.38l0.49,-0.04l0.59,0.63l-0.18,-0.69l0.47,-0.67l-0.59,0.03l0.33,-2.34l0.67,-0.01l-0.25,-0.41l1.85,-2.08l-0.66,0.1l-0.75,-1.14l0.35,-0.33l1.27,-0.16l0.44,0.71l-0.47,0.58l0.64,0.08l0.4,0.47l0.43,-0.99l0.64,-0.04l0.26,-0.69l-0.13,-0.94l-2.05,-0.17l-0.39,0.3l-2.2,-1.49l-1.08,-0.08l-0.02,0.73l-0.48,-1.26l0.71,-0.84l1.78,-0.46l5.28,1.13l0.93,-0.25l0.74,-0.72l-0.03,0.39l0.5,-0.18l0.68,-0.44l-0.1,-0.48l0.4,-0.02l-0.67,-0.52l1.69,-2.59l0.55,0.29l0.32,0.94l0.42,0.06l-0.76,-1.37l0.08,-0.97l1.12,-0.63l1.35,0.22l-0.52,-0.49l0.13,-0.29l-0.53,0.34l-0.46,-0.16l0.79,-0.87l1.52,-0.32l0.23,1.11l-0.22,0.24l1.02,-0.1l-0.64,-0.22l-0.45,-1.49l-1.15,0.17l-0.79,0.47l-0.44,-0.18l2.46,-1.28l0.34,0.11l1.23,-2.11l1.11,0.07l0.49,0.58l-1.42,-0.3l-0.11,1.06l1.12,0.26l-0.34,0.61l0.52,0.17l0.65,-0.6l0.23,0.28l0.98,0.08l-0.38,-0.76l0.12,-0.73l1.38,-0.38l0.76,0.14l0.19,-0.38l0.31,0.18l-0.95,-1.1l0.08,-0.28l1.17,-0.73l0.68,-0.03l0.47,-0.64l1.23,0.44l1.13,-0.85l0.41,0.22l0.31,-0.4l-0.2,-0.37l1.14,-0.4l0.6,-0.56l-0.1,0.75l0.5,0.98l1.11,-1.42l0.78,-0.51l-0.29,0.91l0.25,0.4l0.78,-0.01l1,-0.96l0.41,0.67l0.99,0.35l-0.37,-1.81l0.43,-0.38l0.03,-0.87l0.82,0.15l-0.27,0.54l1.69,-0.49l-0.05,0.43l0.45,0.25l0.38,-1l2.15,-0.06l-0.05,-0.73l0.52,-0.5l0.95,0.2l0.28,-0.3l2.34,-0.43l1.07,-0.7l0.81,0.15l1.03,-0.28l2.15,-1.27l0.97,-0.15l2.43,-1.6l-0.14,-0.92l-0.3,0.84l-3.15,1.33l-0.47,-0.31l-0.29,-1.39l-0.45,0.9l0.36,0.87l-0.42,0.32l-1.13,-1.75l-0.46,-0.17l0.29,-1.06l0.39,-0.27l-0.56,-0.06l-0.28,0.63l-0.87,0.25l-1.1,0.87l1.4,0.85l-0.82,0.3l-0.77,-0.32l-0.55,0.28l0.48,-0.94l-0.37,-0.35l0.01,-0.77l-0.48,-0.13l1.17,-0.87l-0.06,-1.26l-0.34,-0.44l1.06,-0.53l-0.23,0.92l0.52,0.41l-0.11,0.43l1,-0.62l0.31,-0.55l-0.31,-0.34l0.6,-0.5l-1.14,-0.55l0.62,-0.6l0.44,0.75l0.77,-0.76l0.56,0.47l-0.23,0.48l-0.73,0.42l0.51,0.29l0.21,0.57l-0.4,0.66l0.17,0.2l0.5,-0.06l0.46,-0.56l0,-0.82l0.3,0.49l1.08,-0.75l0.23,0.49l1.72,0.09l-0.35,-0.5l-0.66,-0.23l-0.19,-0.5l-1,-0.13l-0.26,-0.49l0.23,-0.28l1.57,0.29l0.95,-0.18l0.2,-0.35l0.7,0.83l0.82,-0.74l0.78,-0.14l-0.16,0.61l0.61,0.28l0.02,0.86l0.59,-0.33l0.73,0.06l-0.41,-0.83l0.66,-0.24l0.72,0.23l-0.32,-0.41l0.33,-0.4l-1.75,0.02l-0.11,-0.42l0.47,-0.22l1.87,0.04l0.58,1.2l0.92,0.53l0.87,-0.73l0.65,0.5l1.12,-1.74l0.34,0.34l1.05,0.11l0.17,0.37l1.39,-0.11l1.61,1.21l0.39,-0.27l0.06,0.33l0.89,0.33l-0.68,0.51l-0.34,-0.37l-0.81,0.74l0.3,0.43l0.65,0.05l-2.23,3.33l-1.54,1.55l0.71,1.29l0.32,-0.14l0.65,-1.7l1.85,-1.92l0.54,0.74l0.52,-0.46l0.66,0.18l0.21,-0.26l-0.28,-0.1l0.12,-0.51l-0.49,-0.22l0.86,-0.29l0.22,-0.47l0.93,-0.02l-0.36,0.93l1.12,-0.2l0.27,0.25l-0.28,0.8l-1.72,2.34l0.26,0.17l1.13,-0.57l0.51,-0.61l0.71,0.45l0.22,-0.64l0.92,-0.6l0.2,-1.06l0.32,0l1.9,-1.8l0.7,0.06l-1.4,0.96l-0.16,0.35l0.67,0.73l-0.68,0.54l0.03,0.28l0.93,-0.01l0.31,-1.31l0.69,-0.19l0.28,-0.43l0.52,-0.1l1.14,0.83l0.32,-0.36l0.71,0.18l-0.51,-1.5l-0.9,0.03l-0.66,-0.59l1.81,-1.34l0.27,0.07l-0.13,0.45l0.6,0.14l-0.16,0.34l0.25,0.32l0.78,-0.46l0.22,0.2l0.39,-0.65l0.63,0.14l0.18,-0.6l-0.85,-0.06l-0.23,-0.47l-0.34,0.34l-0.55,-0.33l0,-0.37l0.52,-0.43l0.55,0.13l-0.07,-0.33l0.62,-0.56l1.67,-0.26l1.79,-1.88l1.25,-0.8l0.3,0.24l-0.58,1.49l1.01,0.1l0.15,-0.63l1.05,0.42l1.55,0.1l0.11,0.46l-1.09,1.18l0.06,0.27l0.37,0.45l1.41,-0.13l1.05,-0.78l-0.18,1.13l-0.99,0.58l0.13,0.25l1.11,0.06l0.27,-0.81l0.83,-0.68l-0.08,-0.59l-1.03,-1.17l-0.29,-1.45l-1.33,-1.04l-0.02,-0.67l-0.56,-0.98l-1.51,-0.21l-0.52,-2.23l-1.01,-1.49l0.08,-0.64l0.36,-0.46l0.55,-0.04l3.29,1.63l1.71,0.1l2.42,-0.65l1.48,0.09l0.38,0.4l3.66,-1.41l0.71,-0.75l0.41,0l0.14,-0.54l0.82,-0.43l0.52,-3.85l0.61,-0.23l0.27,-0.77l-0.22,-0.98l-1.71,-0.86l-0.72,-2.57l0.95,-3.66l0.74,0.08l0.07,0.44l0.35,-0.03l0.38,-0.71l0.35,-0.03l-0.06,-1.56l0.56,-0.69l-0.49,-0.01l0.1,-0.47l-0.57,0.22l0.95,-1.96l2.29,-3.36l0.68,-1.48l2.04,-2.43l0.23,-0.98l0.6,-0.04l1.27,0.91l-0.66,-1.4l0.79,-0.42l0.72,0.13l-0.37,-0.15l0,-0.61l1.69,-2.83l-0.06,-0.38l0.5,-0.39l0.35,0.13l-0.1,-0.3l1.71,-0.95l0.3,-0.51l-0.12,-0.38l0.35,0.13l1.04,-2.07l1.09,-0.31l0.14,0.98l1.63,-0.28l3.21,-3.51l0.41,0.42l0.75,-0.59l0.44,0.44l0.12,0.69l-0.43,0.39l0.91,0.95l1.68,-1.13l0.54,-0.07l0.62,0.37l0.01,1.21l0.37,0.22l-0.29,0.48l1.19,1.64l0.56,-0.56l2.09,1.51l1.04,0.22l0.73,-0.11l0.51,-0.55l1.74,0.02l-0.29,0.38l0.54,1.3l-0.12,1.18l0.37,1.12l0.35,0.17l-0.14,0.51l1.2,0.86l0.03,0.57l0.81,0.06l-0.48,0.71l-0.66,0.19l-0.5,-0.5l-1.59,-0.47l-0.55,0.46l-1.82,0.29l0.05,0.68l0.4,-0.22l0.07,-0.45l1.57,-0.26l0.14,0.2l-1.65,2.26l-0.5,-0.26l-0.26,0.52l-0.36,-0.11l-1.26,0.77l0.85,-0.41l1.47,-0.08l0.14,0.61l-0.97,1.44l-3.77,2.02l-0.81,-0.33l-0.82,0.12l-1.28,1.33l-1.2,0.06l-0.97,1l0.56,0.39l0.96,0.07l0.57,-0.4l1.3,0.11l0.42,-0.74l0.68,1.04l1.51,0.5l0.99,-1.01l0.52,0.52l0.67,0.08l1.77,-0.98l1.14,0.22l1.01,-1.2l-0.42,0.9l0.07,1.23l-0.94,0.79l0.4,0.55l-0.83,0.23l-0.79,-0.28l-0.75,0.48l0.08,0.37l0.45,-0.26l0.54,1.06l0.62,-0.15l0.34,-0.47l1.12,-0.01l2.03,-2.14l1.66,0.43l0.46,1.28l0.37,-0.06l0.5,-0.75l0.44,1.08l0.64,-0.27l-0.69,-0.29l0.16,-0.52l0.6,-0.01l-0.24,-0.69l0.8,0.01l0.76,0.8l-0.15,0.4l0.97,-0.08l-0.52,0.64l0.17,0.16l2.21,-0.58l-0.69,0.52l0.79,0.76l-0.1,0.7l0.37,0.54l1.06,0.48l-0.26,0.51l-1.84,0.47l1.1,0.55l-1.15,0.88l0.02,0.41l0.53,-0.39l0.12,0.21l-0.56,0.93l-1.43,0.42l-0.04,1.53l-0.48,0.14l-0.46,0.76l-0.93,-0.23l0.09,1.2l0.41,0.17l0.01,0.31l-0.47,0.93l0.05,0.93l-0.46,0.58l0.15,0.54l-0.67,1.03l-0.37,-0.25l-0.35,-1.17l-0.85,0.32l0.66,1.06l-0.43,0.58l0.7,0.85l0.3,-0.04l-0.08,0.43l1.02,-0.29l0.34,-0.4l0.66,1.4l0.16,-1.34l1,0.09l2.28,-0.89l0.81,0.1l1.15,0.79l0.53,-0.05l1.3,-1l0.84,-1.44l0.19,-1.66l-0.42,-1.02l-0.03,-1.9l0.44,-0.43l1.47,0.13l-0.14,-0.42l0.47,-0.23l1.35,0.94l1.51,0.43l1.85,-0.46l1.15,-0.89l1.12,0.13l1.41,-0.99l0.42,0.19l-0.34,0.36l1.65,0.15l1.05,1.18l0.84,0.17l-0.15,0.39l0.99,-0.62l0.21,1.21l0.21,-1.1l2.07,-1.3l1.66,-0.46l0.66,0.1l-0.06,0.69l1.44,0.34l0.85,-0.16l-0.28,-0.31l1.24,-0.72l0.78,0.47l-0.68,1.04l0.4,0.31l-0.11,0.76l0.66,-0.43l1.86,0.45l0.25,-0.41l1.27,0.74l0.1,0.59l-1.25,-1.03l0.25,0.5l-0.66,1.48l0.85,-0.03l-0.62,0.5l0.97,-0.04l1.39,1.06l0.58,0.64l0.16,1.06l0.81,0.51l0.6,1.85l0.49,0.42l0.41,-0.52l0.23,0.71l1.48,1.53l0.67,1.16l0.84,0.56l-0.51,0.79l-0.04,2.76l-0.45,-0.04l-0.76,-0.9l-0.69,0.09l0.71,0.85l-0.17,0.37l0.74,0.19l-0.25,0.36l0.77,-0.02l-0.06,-0.33l0.58,-0.16l-0.08,0.78l0.44,1.05l0.15,0.98l-0.3,0.61l-0.9,0.59l-0.59,-0.14l-0.14,0.32l0.93,0.02l-0.17,0.22l0.41,0.09l0.03,-0.54l0.8,0.31l0.37,0.57l-0.17,-1.01l1.1,-0.47l-0.09,-0.82l-0.39,-0.31l0.36,-0.76l0.52,-0.16l0.35,0.31l0.04,-0.42l0.48,0.08l0.77,0.82l-1.31,-1.87l-1.09,-0.26l-0.39,-1.22l0.26,-0.3l1.39,0.24l0.13,-0.55l0.56,0l0.39,1.01l-0.32,0.21l0.77,0.44l0.38,1.07l0.3,1.69l-0.24,0.65l0.56,1.92l0.22,2.71l-0.3,0.45l0.38,0.68l-0.11,0.36l0.34,0.48l-0.34,-1.71l0.39,-0.3l0.49,0.28l0.46,-0.75l0.52,0.81l0.23,-0.3L675.9,258.6zM415.34,135.95l0.28,1.15l-0.62,0.48l-5.29,0.3l-0.57,-0.55l-0.21,-1.89l-0.83,0.39l-0.46,-0.3l-0.47,0.48l-0.86,-0.73l-1.31,-2.38l-0.02,-1.55l0.4,-0.44l0.61,0.11l1,0.71l-0.09,0.41l-0.47,-0.08l-0.11,0.25l0.66,0.51l0.87,-0.89l0.99,0.21l5.09,3.47L415.34,135.95zM429.63,342.75l-0.22,0.78l-0.65,-0.05l-0.54,0.39l-0.9,-0.44l-1.39,-0.04l-1.26,-0.48l-0.35,-0.67l-1.37,-0.9l-0.04,-1.27l2.5,-3.37l0.8,-1.79l0.86,-0.75l0.75,0.11l-0.97,0.27l1.44,1.69l0.99,2.27l-0.02,0.3l-0.33,-0.08l0.51,2.39l-0.25,0.45L429.63,342.75zM423.92,81.04l-0.71,-0.26l-0.4,-0.67l0.4,-1.64l1.48,-2.67l2.66,-1.14l1.35,0.1l2.76,1.1l0.87,0.94l0.05,1.29l-0.34,0.62l-2.62,1.85l-4.21,0.58L423.92,81.04zM450.01,400.97l-0.49,-1.39l0.66,1.2L450.01,400.97zM588.21,147.16l-0.14,0.38l-0.13,-0.45L588.21,147.16zM577.23,177.58l0.57,-0.4l0.46,-1.11l0.02,-0.77l-0.38,-0.23l0.55,-0.89l0.19,-1.79l2.2,-1.53l-1.53,0l-0.32,-0.28l0.3,-2.03l2.02,-4.82l0.3,0.03l0.47,1.01l2.6,1.07h0.69l-2.19,-1.6l-0.31,-1.16l0.31,-0.37l-0.75,-0.72l1.47,-5.78l0.45,-0.27l2.15,1.62l1.26,0.5l0.38,-0.16l-1.77,-1.26l-0.55,-0.66l0.2,-0.57l-0.43,0.25l-1.38,-0.84l0.34,-1.48l0.81,-1.02l1.62,-0.08l-1.58,-0.83l0.74,-2.98l0.89,-0.52l0.8,0.44l-0.12,-0.45l0.65,0.13l0.23,-0.25l-0.1,-0.98l-0.51,-0.74l-0.06,-1.45l0.47,-1l0.34,0.11l0.38,-0.57l0.8,-0.13l0.91,3.99l-0.19,0.54l2.13,0.99l0.15,0.58l-0.69,-5.85l0.69,-2.48l1.08,-0.49l0.51,0.83l2.55,1.19l0.4,1.47l0.42,-0.13l-0.2,0.74l0.53,-0.23l-0.07,0.76l0.56,-0.34l0.4,0.48l-0.73,1.68l-0.29,-0.15l-0.7,1.58l-0.42,0.11l0.25,0.25l-0.77,2.81l0.28,0.85l-0.84,1.94v3.5l0.23,0.15l-0.43,1.52l-1.12,0.97l0.18,0.22l-0.4,0.36l-0.06,1.24l-0.75,2.01l0.71,-0.25l0.26,0.2l0.94,-1.85l0.42,0.3l0.23,-0.28l-0.3,-0.14l-0.05,-1.21l0.56,-0.13l-0.03,-0.68l1.28,-4.15l0.04,-1.34l1.01,1.06l-0.12,-0.51l0.28,-0.33l1.59,-0.96l0.12,-1.11l0.39,0.2l0.5,-0.39l0.18,-1.91l0.35,-0.78l0.24,-0.09l-0.01,0.63l0.38,-0.49l0.05,0.22l-0.14,2.57l0.44,-1.34l0.73,-0.24l-0.05,-0.74l0.41,-0.48l-0.02,1.52l1.21,0.05l0.17,0.26l0.01,1.64l-0.52,0.73l0.75,1.28l-0.19,1.12l0.4,0.18l0.58,-0.43l1,0.42l1.24,2.17l-0.08,1.94l0.47,0.01l-0.13,0.39l0.51,-0.47l0.53,0.36l-1.32,0.81l-2.7,-0.68l-0.35,0.33l0.73,0l0.83,0.6l0.4,-0.18l0.89,0.23l1.21,0.79l0.11,1.18l-0.37,0.4l-0.21,1.29l1.56,-2.88l-0.46,-0.18l0.05,-0.36l0.79,-0.71l1.33,0.73l1.17,1.18l0.78,2.62l-0.49,-0.09l-0.03,0.54l0.6,0.38l-0.12,1.69l0.59,4.16l-0.37,1.67l-1.29,2.91l-2.19,3.5l-0.52,0.3l0.05,-0.43l-0.52,-0.35l-1.53,0.57l-2,-0.05l-2.38,2.06l-1,0.18l-0.15,0.38l-1.51,-0.15l-1.27,0.53l-0.54,0.59l-1.33,-0.33l-0.89,0.64l0.18,0.77l-1.4,1.12l-0.04,-0.57l0.48,-0.28l-0.57,-0.64l0.13,-0.84l-1.63,0.15l-0.53,0.33l-1.05,-0.14l-1.54,0.94l-0.54,-0.54l0.69,-0.75l-0.28,-0.59l-0.63,1.31l-1.88,0.33l-1.19,-0.33l-0.32,0.22l0.46,-0.87l-0.18,-0.1l-0.54,0.97l-1.72,0.63l-2.84,3.12l-1.8,0.98l-3.65,3.49l-1.3,-0.03l-0.06,-0.4l-0.95,0.13l-0.9,0.92l-0.6,-1.04l-0.13,-1.88l-0.52,-0.38l1.83,-5.46l0.58,-0.61l0.46,-1.36l1.97,-3.51L577.23,177.58zM579.69,171.17l-0.15,0.44l-0.25,-0.03l0.02,-0.33L579.69,171.17zM582.56,162.95l-0.09,0.29l-0.26,-0.14L582.56,162.95zM610.72,181.69l-0.08,-0.23l0.32,-0.06L610.72,181.69zM601.08,152.11l-0.19,0.21l0.1,-0.86L601.08,152.11zM574.37,194.19l0.16,-0.34l0.25,0.09L574.37,194.19zM561.47,112.45l0.06,0.71l1.14,0.85l0.1,0.59l-1.53,1.58l0.6,1.93l-0.42,0.74l0.65,0.41l-0.4,1.39l-0.93,0.55l-1.06,1.53l-1.09,-0.31l-0.95,0.13l1.18,0.47l0.12,0.31l-4.13,2.12l-0.47,0.68l-1.15,0.08l-2.24,1.91l0.24,0.34l0.66,-0.33l0.5,0.14l1.52,-1.07l0.58,-0.03l0.27,0.83l0.13,-1l0.76,-0.54l0.13,-0.45l0.87,-0.6l3.33,-1.02l-0.07,1.6l-1.13,1.01l-1.4,0.5l-0.34,0.96l-0.76,0.43l-0.34,1.55l0.25,1.03l-0.33,0.71l0.31,0.93l0.08,-3.19l2.21,-1.99l1.02,-0.48l0.61,-0.99l0.78,0.5l-0.04,-1.85l0.55,0.01l0.38,-0.59l0.58,0.01l0.98,-0.59l0.49,0.07l-1.05,-3.36l0.41,-0.42l0.29,0.41l0.71,0.11l0.55,-0.87l0.01,-1.41l0.35,-0.23l-0.14,0.75l0.34,-0.31l0.32,0.19l-0.67,1.81l-0.04,1.15l0.44,-0.41l0.27,0.22l-0.15,-1.23l0.6,-1.75l0.06,-1.41l-0.62,-0.83l-0.14,-1.14l0.51,-0.85l1.25,-0.74l0.23,0.12l-0.46,0.96l0.56,0.54l0.5,-0.28l0.39,-0.83l0.28,0.12l0.1,0.62l0.87,-0.73l1.8,0.02l0.01,0.36l-1.06,0.71l0.05,0.41l1.61,-0.41l0.39,0.46l-0.75,0.59l-0.08,0.57l1.54,0.08l-0.45,0.41l1.11,0.15l0.22,0.43l-0.31,0.2l-0.25,1l0.21,0.09l0.34,-0.71l0.59,0.67l-0.19,0.59l0.73,-0.03l0.56,0.94l0.04,1.43l0.69,0.24l-0.1,0.55l0.36,-0.28l0.11,0.19l0.22,1.87l0.36,0.74l-0.42,0.89l-0.73,0.51l-0.76,-0.23l-0.15,0.22l0.14,0.27l0.3,-0.09l-0.05,0.51l0.37,0.21l0.09,1.05l-0.35,2.44l-0.48,-0.18l0.2,0.6l-0.22,2.28l-0.61,0.7l0.49,0.25l0.5,1.7l-0.76,2.37l0.35,1.24l-0.36,1.74l0.31,1.01l-0.11,2.52l-0.22,0.22l-0.66,-0.39l0.16,0.6l-0.24,0.48l-0.61,0.27l0.29,0.55l-0.67,-0.75l0.17,-0.14l-1.69,-1.65l-0.62,-0.18l-0.35,0.37l0.09,0.71l1.17,1.96l2.71,2.87l-0.8,0.31l-0.2,0.86l2.29,1.08l0.26,1.46l-0.4,0.9l0.8,2.94l-0.11,0.52l-0.45,0.82l-1.55,1.14l-1.14,1.41l-0.41,1.21l-0.86,-0.21l-0.17,-0.32l-1.55,0.87l-3.75,-0.35l-0.67,0.9l-1.08,0.59l-0.52,-1.16l-0.39,-0.27l-0.55,0.18l-0.45,-0.85l-0.31,0.16l0.31,0.47l-0.6,-0.02l-0.41,-0.59l-0.54,-0.15l-1.89,0.8l-0.73,-0.77l-0.77,-0.2l-0.57,-1.26l0.1,-0.69l-0.61,0.28l-0.9,-0.19l-1.42,-1.86l-0.14,-1.96l-0.61,-0.49l-1.3,0.08l-0.48,0.34l-0.42,-0.39l0.37,-0.36l-0.68,0.45l-0.27,0.6l-1.2,-1.22l-1.02,1.25l-1.07,0.03l-0.66,-0.81l-1.38,0.35l-0.17,-1.62l0.3,-0.85l-0.13,-0.24l-0.55,0.34l-0.24,-1.62l-1.11,0.11l-0.77,1.2l-0.51,0.07l-1.08,1.3l-0.97,-0.35l0.43,-0.26l-0.09,-0.46l-0.56,0.47l-0.57,-0.16l-1.65,-2.76l0.27,-2.43l-2.35,-2.33l0.37,-0.23l-0.44,-0.22l0.19,-0.49l0.19,-0.16l0.04,0.26l0.2,-0.47l-0.47,-1.63l0.24,-1.05l-0.4,-2.53l0.46,-0.95l-0.19,-1.75l-0.55,-0.35l-1.32,0.15l-0.61,-0.32l-0.16,1.06l0.31,0.4l-0.34,0.79l-0.87,-0.43l0.06,0.36l-0.54,0.15l0.33,-1.1l-0.74,-0.53l0.73,-0.57l0.45,0.16l-0.21,-1.26l0.69,0.02l-1.19,-0.67l0.19,-0.4l-0.83,-0.3l-0.09,-0.32l-0.29,0.09l-0.13,-0.33l0.1,-0.31l0.85,-0.08l0.03,-0.56l0.64,-0.37l0.13,-1.49l-1.14,0.64l-0.29,0.87l0.3,0.72l-0.77,0.19l-1.31,1.73l-0.19,0.8l0.64,0.61l-0.92,1l0.57,0.19l0.04,0.28l-1.45,0.27l-0.6,-0.41l-0.23,-0.82l0.9,-0.43l-0.09,-0.49l0.53,0.08l-0.03,-1.14l-0.8,-0.32l-0.71,0.55l-0.48,-0.53l0.28,-0.51l-0.59,-0.61l-0.73,0.07l0.02,-0.61l0.67,0l0.22,0.45l2.01,0.85l0.17,-0.76l1.6,-2.13l0.83,-0.1l-0.25,-0.15l0.85,-1.33l0.42,-1.56l1.88,-2.8l1.8,-0.52l2.52,0.42l0.09,-0.27l-0.96,-0.19l0.88,-0.85l-0.11,-0.79l-0.93,-0.49l-1.75,-2.19l0.03,-1.11l0.38,-0.15l0.39,-0.79l-0.41,-0.29l-0.16,-1.31l0.84,0.68l0.92,-0.76l1.23,0.48l-0.8,-0.91l0.46,-0.19l0.18,-1.74l1.39,-0.94l0.23,-1.64l0.33,0.08l0.12,0.68l0.58,0.28l-0.28,0.82l0.83,0.42l0.63,1.2l0.82,-1.27l0.01,-1.55l0.58,-0.61l1.08,0.32l0.78,-0.32l0.49,0.49l1.76,-0.4l0.56,0.62l0.38,-0.16l0.41,-0.84l0.6,0.56l0.9,0.1l0.89,-0.53l0.27,-1.02l0.93,0.67l2.35,-1.08l0.66,-0.79l3.54,0.1l0.34,0.81L561.47,112.45zM517.23,130.24l0.15,0.55l0.27,-0.1l-0.31,0.27l-3.24,-2.47l-0.43,-1.56l4.77,0.42l-0.7,0.58l1.31,0.85l0.68,-1.82l0.28,0.08l-0.1,-0.31l0.83,-0.03l0.21,0.56l0.54,0.09l0.25,-1.26l-0.35,-0.79l-1.21,-1.14l-1.24,-0.24l-0.59,0.55l-0.36,-0.4l-1.12,-0.34l-0.82,0.12l-2.29,-0.6l-0.49,-1.4l0.4,-0.73l0.42,0.16l0.63,-0.47l0.2,-0.62l-1.53,-1.95l0.83,-0.61l0.1,-1l-0.7,-0.25l-0.21,-1.34l-1.75,-1.13l3.66,-0.28l1.19,0.31l1.77,-0.5l0.39,0.83l0.52,0.36l1.61,0.35l1.78,-0.06l0.51,0.78l2.99,-0.2l2.53,1.11l2.12,2.36l1.14,0.37l0.58,0.53l-0.58,1.87l-0.67,0.68l0.23,0.46l-0.17,0.52l-1.44,1.06l-0.52,-0.17l0.46,-2.03l-1.26,1.85l-1.18,-0.64l0.97,0.94l0.75,-0.49l-0.16,0.64l0.7,0.39l-0.66,0.97l-0.71,0.36l-0.49,1.26l-0.75,0.76l-2.85,1.13l-1.76,0.27l-2.74,-0.45l-1.35,1.05L517.23,130.24zM552.99,127.26l0.04,-0.3l0.21,0.43L552.99,127.26z"
},
{
"id":"RU-LN",
"title":"Leningrad",
"d":"M64.34,566.44l-0.42,-0.12l-0.6,0.24l0.05,0.25l-0.53,-0.17l-0.07,0.87l-1.1,0.41l-0.02,0.89l-0.52,-0.42l-1.19,0.58l-1.49,-0.49l2.73,-3.52l0.48,-0.16l2.13,-2.52l0.86,0.11l0.46,-1.43l0.77,-1.16l0.84,-0.33l1.92,-1.64l0.77,-1.15l0,0l0.78,0.95l0.96,0.4l0.54,0.85l1.18,0l1,0.67l0.85,0.05l18.44,7.19l1.08,0.07l1.25,-1.68l0.61,0.14l0.63,-0.37l0.45,-1.32l1,-1.09l0.78,-0.4l0,-0.65l0.95,0.11l1.27,0.84l0.26,-0.28l0.81,-2.01l-0.93,-0.42l-0.85,0.49l-1.09,-0.85l-0.22,-0.61l2.17,-1.19l2.55,0.32l0.58,-0.27l1.89,1.74l0.24,-1.36l2.13,-1.46l2.53,1.29l1.38,-0.84l-0.02,1.59l0.74,0.52l0.28,0.06l0.8,-1.01l0.52,0.55l0,0l0.26,1.02l-0.38,1.06l-0.98,0.82l0.04,0.49l0.54,0.43l-0.31,0.8l-0.45,0.53l-0.83,-0.4l-0.44,0.15l-0.82,1.06l0.67,1.53l0.33,1.81l-0.74,3.57l-0.55,0.77l-0.14,1.65l0.65,0.53l-0.02,0.57l-0.42,0.41l2.43,0.91l-0.5,0.6l-0.07,2.51l0.19,0.45l1.38,0.3l0.13,1.24l-0.84,-0.61l0.04,1.37l-1.01,1.24l0.59,0.68l-0.62,0.88l-0.23,1.03l-0.81,-0.01l-0.71,0.74l-0.62,-0.19l-0.34,0.57l-0.59,-0.67l-1.07,1.36l0.03,0.58l-0.27,0.12l0.21,0.46l0,0l-1.11,0.05l-2.03,-1.02l-1.18,0.19l-0.35,0.62l-0.5,-0.17l-0.69,-0.58l-0.63,-0.1l-1.45,-2.56l-1.14,0.28l-0.65,-0.24l-0.73,0.88l-1.54,-1.06l-0.43,-0.7l-0.67,1.07l-1.17,0.93l-0.2,0.85l0.29,0.9l-0.44,0.8l-0.67,0.26l-2.18,-1.31l-0.32,-1.58l-2.37,-1.66l-0.38,0.1l-0.34,1.45l-0.38,0.1l-0.37,-0.04l-0.69,-0.86l-1.01,-0.11l0.39,1.94l-0.53,0.4l-0.01,0.75l-0.87,1.38l-0.94,0.37l-0.84,-0.6l-0.78,-0.02l-0.67,1.84l-1.32,1.1l-0.31,1.45l-0.4,0.17L78.24,594l-1.22,0.73l-1.39,-0.86l-0.22,0.15l-0.22,0.4l0.28,0.46l-0.42,0.68l0.36,0.98l-0.02,1.13l-0.87,0.61l-0.77,-0.29l0,0l-0.79,0.43l-0.83,-0.09l-0.63,-0.39l-0.42,-1.01l-1.9,-0.6l-0.16,-1.2l-1.86,-1.84l-0.81,0.07l-3.48,-0.95l-0.67,0.07l-0.95,-1.62l-0.94,-0.46l-1.06,-0.14l-1,0.98l-0.37,-0.55l0,0l0.15,-0.59l0,0h0l0,0l1.22,-3.3l0.89,-0.72l0.64,-0.01l0.05,-0.51l0.59,-0.46l-1.18,-1.44l0.36,-1.58l-0.67,-1.55l0.18,-0.8l0.51,-0.54l0.63,0.17l0.26,1.3l1.03,0.39l0.48,-0.3l0.29,-2.1l0.61,-0.32l1.23,1.09l1.68,-0.5l0.73,-0.9l-0.01,-0.3l-0.54,-0.29l0.4,-0.12l0.09,-0.52l0.48,-0.41l0.74,-0.13l3.36,0.89l0,0l-0.14,0.99l0.77,0.55l0.48,-0.05v0.32l1.53,1.67l1.25,1.05l0.9,0.15l1.08,-0.4l0.39,-0.88l0.82,0.01l0.64,-0.71l-0.09,-0.47l-1.73,-1.06l0.05,-1.93l-1.24,-0.93l0.23,-1.11l-1.82,-0.41l-3.52,-1.58l-0.7,0.15l-0.94,1.34l0,0l-1.9,0.02l-0.86,-0.29l-0.21,-0.83l-0.98,-0.69l-0.34,-0.95l-0.28,0.51l-1.09,-0.51l-1.24,-2.81l0.37,-0.01l0.5,1.02l1.05,0.59l-0.4,-1.19l0.18,-0.55l-0.24,-0.49l-0.29,0.5l-0.4,-0.66l0.17,-0.61l0.31,0.57l0.62,0.17l-0.42,-0.9l0.76,-0.14l-0.19,-0.34l0.27,-0.57l-0.38,-0.68l-0.27,0.05l0.12,0.44l-0.31,0.05l0.08,0.82L64.34,566.44zM58.04,590.1l0,0.01l0,0h0l0,0L58.04,590.1z"
},
{
"id":"RU-LP",
"title":"Lipetsk",
"d":"M138.18,660.53L138.53,660.73L139.04,660.5L139.38,660.78L140.26,662.68L141.18,662.3L141.68,662.53L142.81,662.3L143.01,661.19L144.3,660.4L144.47,660.8L144.85,660.52L145.69,661.02L145.69,661.89L145.4,661.96L145.98,662.61L146.79,662.77L147.38,663.47L147.38,663.47L146.88,664.96L147.22,666.87L147.04,667.38L147.5,667.66L146.79,668.55L147.28,669.61L147.02,669.93L146.39,669.86L146.03,670.63L146.81,672.71L148.84,673.81L148.61,674.38L148.94,674.8L150.28,675.19L151.74,676.44L151.7,677.09L150.99,677.44L150.32,679.74L150.32,679.74L146.02,679.53L145.58,680.08L144.48,680.09L143.06,679.56L142.89,678.46L142.23,678.13L140.18,678.04L140.01,679.09L139.55,679.29L138.85,678.86L138.42,678.03L137.86,677.83L137.49,678.12L136.87,677.82L136.44,678.77L135.61,678.52L134.07,679.47L134.07,679.47L133.43,679.87L132.77,679.71L131.66,680.01L130.51,679.51L130,678.4L130,678.4L129.99,677.01L131.37,675.93L131.74,676.12L132.09,675.86L132.29,675.24L131.73,674.55L131.78,674.16L131.33,674.17L131.16,673.76L131.52,673.42L130.68,673.16L130.56,672.87L130.98,672.62L130.1,671.85L129.5,671.91L129.46,671.48L130.02,671.46L130.82,669.97L130.5,669.26L130.79,668.42L130.38,667.92L130.61,667.04L130.61,667.04L131.04,667.03L130.98,666.45L131.63,666.46L131.73,666.74L133.63,666.6L133.97,667.81L134.57,667.58L134.59,667.2L134.93,667.34L135.28,666.43L135.57,666.4L135.66,667.07L136.17,667.01L136.14,666.5L136.41,666.58L136.74,665.93L135.86,665.09L136.39,664.94L135.48,663.43L137.53,662.83L137.07,661.76L137.34,661.63L136.85,661.36L137.72,660.7L138.15,660.99z"
},
{
"id":"RU-MOW",
"title":"Moscow City",
"d":"M124.57,633.65l-0.01,0.01l0,0l0.44,0.4l0.55,-0.18l-0.17,-0.14l0.19,0.29l-0.86,0.21l-0.31,-0.28l0.31,-0.16l-0.42,0.11l-0.03,-0.29l-0.4,0.29l0.71,-0.3l0,0L124.57,633.65zM130.85,632.75l0.3,0.01l0,0l-0.31,0.13l0,0L130.85,632.75zM124.36,640.22l0.03,-0.39l0.52,-0.26l-1.22,-1.17l-0.39,-0.75l0.08,-0.86l0.86,-0.12l0.28,0.75l0.62,-0.1l0.64,0.3l-0.41,-0.33l0.34,-0.12l-0.32,-1.6l0.95,-0.25l0.66,-0.56l0.69,0l-0.1,-0.43l-0.51,0.22l0.24,-0.35l0.2,0.13l-0.16,-1.15l-0.36,0.28l-0.09,-0.39l0.42,0.09l0.19,-0.51l-0.29,0.11l-0.15,-0.32l0.57,-0.33l-0.53,-1.06l0.6,0.04l-0.22,0.49l0.27,0.45l0.78,-0.4l-0.12,-0.44l0.4,-0.17l-0.12,0.58l0.96,0.16l1.05,0.9l0.04,1.01l0.92,0.47l-0.03,0.5l-0.35,-0.04l-0.1,-0.4l-0.3,0.09l-0.95,1.41l-0.97,0.21l-0.14,0.66l0.23,0.4l-0.48,0.22l-0.06,0.45l-0.65,-0.57l-0.37,0.17l-0.15,0.3l0.69,0.69l-0.47,0.67l0.16,0.27l-0.32,-0.02l0.17,0.83l-0.63,0.38l-0.32,-0.47l-0.01,0.23l-0.4,-0.15l-0.36,0.27l0.06,0.83l-0.43,0.22l0,0l-0.33,0.04l0,0l-0.14,0.05l0,0l-0.6,-0.81l0,0l0.01,-0.01l0,0l0.01,-0.02l0,0l-0.03,-0.05l0,0l-0.02,-0.02l0,0l-0.01,0l0,0l-0.08,-0.18l0,0L124.36,640.22zM127.8,630.65l0.12,0.02l0,0l-0.62,0.31l0.22,-0.31l0,0L127.8,630.65zM125.75,630.9l-0.11,-0.66l0.42,-0.07l0.56,0.5l-0.4,0.09l-0.06,0.35l0,0l0,0l0,0L125.75,630.9L125.75,630.9L125.75,630.9z"
},
{
"id":"RU-ME",
"title":"Mariy-El",
"d":"M194.45,617.83L197.05,618.13L197.46,618.67L197.29,619.27L198.95,618.75L199.82,619.05L199.94,618.24L201.62,616.25L202.47,617.05L203.81,616.96L204.55,616.71L204.58,616.04L205.12,615.84L205.37,615.02L206.08,615.02L206.53,615.58L207.28,614.74L208.16,615.11L209.09,614.67L209.55,614.99L209.28,615.71L210.07,616.02L210.36,615.86L210.5,614.99L211.08,614.5L210.72,613.84L210.89,613.12L212,612.8L212.29,613.26L211.84,614.01L211.86,614.78L212.47,616.45L213.17,616.76L213.87,616.21L215,615.94L216.01,616.5L215.91,616.96L216.21,617.46L215.92,618.44L217.33,618.85L217.76,618.68L218.38,619.07L218.68,619.96L218.2,621.63L218.2,621.63L218.33,622.21L218.94,622.29L219.21,622.74L219.16,623.04L218.34,623.36L217.83,624.26L217.39,623.8L216.5,624.41L216.2,623.95L216.54,623.43L215.96,623.09L214.91,623.48L214.5,624.39L213.68,624.28L213.2,625.26L211.37,624.83L210.35,625.46L209.82,626.4L210,626.94L211.11,626.96L211.03,627.36L210.46,628.17L209.74,628.15L209.17,629.27L208.28,629L207.85,630.37L206.33,631.54L206.45,632.36L206.45,632.36L203.56,630.82L202.71,628.61L200.55,628.25L199.74,627.78L199.13,626.16L198.7,625.79L197.5,625.91L194.88,627.68L194.17,628.55L193.67,628.64L192.81,628.19L190.09,629.99L190.09,629.99L189.63,628.72L189.71,628.01L188.08,626.81L188.79,625.89L188.72,625.06L187.46,624.23L186.54,624.42L186.35,623.86L186.64,622.71L187.31,621.94L188.35,622L188.23,619.71L188.79,618.96L190.94,618.5L191.61,617.65L193.11,618.14L193.67,617.99L194.05,617.33z"
},
{
"id":"RU-MAG",
"title":"Magadan",
"d":"M996.22,475.53l0.96,0.08l0.26,0.83l1.61,1.03l1.96,0.11l-0.08,0.65l-1.33,1.83l-0.49,1.27l-0.07,4.2l1.16,1.32l4.58,1.67l0.59,0.92l2.01,0.43l0.67,2.05l2.97,3.52l4.78,0.87l1.63,1.18l1.09,0.19l1.59,3.27l1.44,1.01l3.39,0.58l1.5,1.57l3.18,-0.13l0,0l0.05,2.13l1.28,1.33l-0.01,0.72l0.69,0.79l-0.02,0.53l-1.86,1.36l-0.11,0.45l0.38,0.49l-0.58,0.49l-1.58,0.21l-0.87,0.62l-0.18,0.8l0.82,1.36l0.1,2.04l-0.61,0.52l-0.69,1.71l0.7,0.56l0.04,0.69l0.76,0.32l0.45,0.81l0.07,1.25l-1.21,1.73l-1.11,0.38l0.35,1.33l-0.35,0.78l0.61,0.6l-0.06,0.37l-0.88,0.4l-0.67,0.99l-0.72,0.2l-0.6,-0.28l-0.48,0.6l-0.5,2.15l0.07,0.9l1.04,0.27l1.64,1.58l-0.54,0.78l1.68,0.74l-0.17,0.7l-0.89,0.81l0.85,1.7l-0.31,0.9l-0.02,1.83l-1.6,1.07l-2.22,0.71l-0.16,0.61l0.51,0.52l1.64,0.34l0.36,1.06l-0.95,1.13l-0.53,-0.09l-0.42,0.4l0.63,1.58l0.74,0.75l-0.21,0.96l0,0l-0.44,0.06l-0.14,0.83l-0.46,-0.02l0.27,0.36l-0.51,0.61l-0.37,-0.11l0.12,0.58l-0.64,0.35l-0.22,0.85l-0.72,0.04l0.38,0.22l-0.29,0.5l-0.62,0.11l-0.35,-0.81l0.14,1.39l-0.28,0.04l-0.3,-0.56l-0.29,1.09l-1.1,0.71l-0.54,-0.04l0.36,0.31l-0.14,0.68l-0.67,-0.17l-0.65,0.68l0.38,0.47l-1.04,0.97l-0.69,0.04l-0.46,1.31l-1.58,1l-0.94,2.65l-0.71,-0.72l-0.36,0.72l-0.7,-0.35l-0.58,0.67l-0.39,-0.11l0.07,-0.67l-0.57,0.36l0.28,0.18l-0.05,0.56l-0.54,0.44l-0.09,0.48l-0.92,0.54l-0.04,-1.22l0.41,-0.1l-0.03,-0.52l0.36,-0.27l-0.04,-0.88l-0.5,-0.68l0.24,-0.27l0.28,0.16l0.16,-1.05l0.77,-0.01l-0.3,-0.35l0.6,-0.89l0.05,-0.7l-0.48,-0.19l-0.68,0.37l-0.52,-0.28l-1.84,1.48l-0.37,-0.09l0.1,0.43l-0.8,-0.18l1.5,-2.68l-0.19,-0.96l-0.43,-0.53l0.26,-0.19l-0.22,-0.42l-1.01,0.22l0.46,-0.8l0.44,-0.02l0.44,0.41l0.28,-0.32l-0.71,-0.37l0.54,-0.39l-0.04,-0.56h0.7l0.23,-0.96l-0.47,-0.16l1.69,-1.47l-0.16,-0.63l0.55,-1.17l-0.42,-0.36l1.05,-1.12l-0.09,-0.57l-0.28,-0.02l0.31,-0.4l-0.16,-1.23l-0.45,-0.42l-2.03,1.47l-1.05,2.01l-0.67,-0.2l-0.09,0.35l-0.41,0l-0.22,-0.35l0.02,0.58l-0.88,0.45l-0.35,-0.2l-0.06,-0.52l0.43,-1.97l-0.43,0.53l-0.69,0.21l-0.55,-0.59l0.4,-0.56l-0.23,-0.4l-1.29,-0.51l-1.25,-0.05l-0.34,0.43l-0.53,-0.09l-0.38,1.27l-0.61,0.02l-0.39,-0.33l-0.98,0.09l-0.57,0.67l-0.63,-0.52l-0.99,0.02l-1.58,1.41l-1.55,-0.81l-2.38,-0.11l-0.83,0.85l-0.19,0.81l-0.61,-0.26l-1.53,0.71l-1.05,1.71l-0.59,0.3l-1.03,-0.01l-0.32,2.15l0.12,2.59l-0.26,0.17l-0.2,-0.39l-0.67,0.31l-2.71,2.54l-0.62,0.99l-0.69,0.12l-0.14,0.24l0.42,0.33l-0.36,0.5l-0.09,2.31l-0.66,-0.23l-0.68,1.15l-0.72,0.1l-1.05,1.01l-0.3,0.87l-0.77,-0.1l-1.24,1.57l-1.26,0.62l-1.14,1.03l-1.78,2.92l-0.52,-0.03l-0.65,0.44l0.53,2.61l-1.16,-0.16l-0.75,0.31l0.03,1.92l1.04,2.26l-0.59,-0.57l-0.1,-0.6l-0.34,-0.03l-0.58,1.83l-0.29,-0.09l-0.25,0.33l0.4,0.81l1.26,0.31l0.31,-1.14l0.34,-0.23l0.15,0.41l-0.26,0.44l0.34,0.28l-0.02,0.58l0.74,-0.01l-0.53,-1.01l0.25,-0.41l-0.41,-0.11l-0.12,-0.39l0.99,0.54l0.71,-0.4l1.01,1.09l0.87,-0.08l0.43,-0.38l0.82,1.48l0.89,0.63l0.06,0.56l-0.46,0.2l0.33,0.8l-0.46,0.18l0.33,0.68l-2.51,-0.32l-0.29,0.23l0.1,0.74l-0.93,-0.28l-1.01,-0.96l-1.01,0.29l-0.45,-0.19l0.22,0.19l-0.24,0.07l0.18,1.14l-0.17,-0.2l-0.37,0.53l-0.39,-0.27l-0.41,0.13l-0.9,0.66l-0.74,-0.32l-0.71,-1.37l-1.1,-0.21l0.26,-0.46l0.38,-0.01l0.02,-0.47l-0.98,0.85l-1.92,-0.91l-0.17,1.47l-0.25,-0.23l-0.33,0.46l0.59,0.02l-0.08,0.62l-1.57,0l-0.74,0.3l-0.49,0.81l-0.3,1.42l-0.67,-0.29l-0.63,0.29l-0.46,-0.48l-0.79,-0.13l-0.22,-0.51l-0.79,-0.48l-1.7,0.48l-0.21,0.96l-0.54,0.44l-1.63,0.09l-1.14,0.53l-1.5,-0.32l-0.93,0.38l0.12,-0.28l-0.79,-1.1l-0.1,-0.87l-0.97,-1.49l0.83,0.27l1.75,-1.11l0.91,0.24l0.42,-0.21l0.74,0.49l2.35,-0.23l0.85,-0.72l0.8,0l0.08,-0.44l-1.08,-0.98l-0.23,0.23l-0.02,-0.33l-0.92,0.58l-0.8,-0.61l-1.16,0.1l-0.14,-0.38l0.38,-0.4l-0.56,-0.58l-0.11,-0.67l-0.62,-0.74l-0.54,-0.12l-0.78,-1.39l-0.31,0.01l-0.41,0.64l-1.23,-0.34l-1.58,0.24l-0.18,0.32l0.39,0.31l-0.24,0.42l0.35,0.13l-0.15,0.39l-1.29,0.31l-0.08,-0.79l-1.79,0.05l1.86,-0.64l0.09,-0.46l-1.4,0.29l-0.85,-0.49l0.01,-0.54l-0.53,-0.06l-0.5,-0.51l-1.15,-0.03l-3.73,-1.39l-1.05,0.08l-1.3,0.59l-1.85,1.31l0.37,0.06l0.09,1.03l0.74,0.23l0.08,0.84l-0.91,-0.35l-1.21,0.48l-0.5,-0.47l0.46,-0.62l-0.36,-0.28l-1.13,1.26l0.13,1.4l0.53,0.21l0.6,-0.63l0.03,0.63l0.3,-0.1l-0.12,-0.29l0.45,-0.03l-0.44,0.81l0.27,0.52l-0.24,0.66l-0.63,-0.65l-0.35,0.1l-0.18,0.51l-0.31,-0.02l-0.11,-0.41l-0.96,0.4l-1.13,-0.21l0.18,-0.39l-0.31,-1.34l-0.81,-0.42l-2.97,0.32l-0.81,0.41l0.63,0.72l-0.36,0.58l-1.17,-0.63l-0.68,0.41l0.02,0.59l-1.77,-1.39l-0.94,0.23l-0.52,-0.54l-0.94,-0.18l0,0l1.67,-0.65l0.02,-1.82l0.57,-1.41l-0.16,-1.68l-0.45,-0.44l0.37,-0.4l-0.11,-0.65l-0.84,-0.34l-0.05,-0.89l-0.57,0.05l-0.87,0.87l-0.34,-0.11l-0.81,-1.35l0.45,-0.73l-0.26,-0.77l-1.44,-0.32l-0.73,-1.55l-0.85,-0.26l-0.99,0.58l-0.96,-0.26l-1.03,0.55l-2.27,-2.46l0.53,-0.26l-0.68,-1.04l0.23,-0.61l0.68,-0.19l0,-0.88l1.08,-0.79l0.5,0l0.54,-1.19l0.51,-0.05l0.47,-0.54l0.5,-0.13l1.43,1.18l0.76,-0.02l0.36,-0.65l-0.37,-0.68l0.02,-2.12l0.32,-0.46l1.15,-0.13l0.49,-1.41l-0.15,-0.35l0.41,-0.52l0.05,-1.23l-0.74,-2.26l0.24,-1.02l-0.79,-0.99l0.14,-1.77l-1.14,-1.42l0.03,-0.71l-2.08,-2.82l-1.93,-1.33l-1.04,-0.18l-0.42,-0.95l-0.42,0.34l0.13,0.86l-0.34,0.48l-0.59,0.09l-0.21,0.48l-0.58,-0.01l0.26,-0.78l-0.49,0.12l-0.27,-0.46l-0.39,-0.08l-0.52,0.79l-1.29,-0.76l-0.56,-0.9l-1.78,0.21l0,0l-0.09,-0.93l0.53,-0.17l0.51,-0.71l0.39,0.18l0.61,-1.11l0.67,-0.1l0.3,-0.84l-0.18,-1.2l0.57,-1.15l-0.44,-0.73l0.8,-0.77l0.27,0.28l0.8,-0.24l0.26,-0.4l-0.51,-0.62l0.46,-1.66l-0.62,-0.42l-0.08,-0.64l0.62,-0.97l-0.13,-1.92l-1.4,-1.13l0.49,-0.58l-0.01,-0.71l-0.65,-0.89l0.29,-0.92l0.93,-1.21l-0.09,-0.71l0.61,-1.37l-0.15,-0.83l1.08,-1.46l0.5,-1.69l-0.33,-1.95l0.2,-0.69l3.47,-1.45l0.87,-1.2l0.71,-2.54l0.42,-0.33l1.2,0.58l2.2,-0.34l2.4,1.85l0.8,0.05l0.21,-0.99l0.74,0.21l1.26,-0.82l0.43,0.44l-0.5,1.39l1.21,0.95l-0.26,0.59l1.25,0.22l0.71,-0.24l-0.09,-0.99l0.3,-0.84l1.65,-2.55l-1.54,-1.97l-0.26,-1.32l0.82,-0.42l1.47,-1.66l0.82,0.42l0.13,0.92l1.06,0.55l0.82,-0.57l0.84,0.72l0.32,-0.76l1.02,0.3l0.79,0.85l0.97,0.1l-0.16,-0.73l0.83,0.37l2.49,-1.85l0.35,-0.73l1.01,0.16l-0.01,0.65l1.15,0.64l-0.05,0.61l-0.71,0.62l0.29,0.62l-0.12,0.92l1.11,0.93l0.26,0.83l1.04,-0.14l1.09,0.68l0.78,0.03l-0.09,-2.27l0.41,-0.67l1.56,0.38l1.17,-0.14l0.74,-0.61l0.33,0.42l0.75,-0.6l0.79,1.03l0.54,-0.19l0.78,-1.73l0.69,-0.01l1.58,-0.72l1.36,0.6l-0.42,1.04l0.49,0.29l1.76,-0.44l0.33,-0.81l-0.81,-1.26l0.21,-0.43l0.97,-0.18l0.7,-1.33l1.43,-0.83l0.33,-0.78l-0.13,-0.48l-1.11,-0.58l-0.93,-3.71l0.92,-0.51l0.08,-1.85l0.6,-0.78l-0.01,-0.56l1.05,-0.28l0.92,-0.75l1.19,0.39l0.59,-0.21l0.01,-0.64l0.45,-0.47l0.83,0l0.6,-0.83l0.14,-0.83l-0.82,-0.74l0.2,-0.95l1.09,-1.36l-0.26,-0.6l0.3,-1.4l-0.51,-0.19l0.21,-1.52l1.08,-0.34l0.52,-0.57l1.31,0.13l0.94,-0.24l0.39,0.47l-0.15,0.98l0.92,-0.04l1.3,-1.97l0.07,-1.3l-0.93,-0.84l-0.2,-0.79l1.25,-0.79l0.03,-0.83l1.11,-0.69l0.65,0.19l0.45,0.52l0.75,0.05l0.32,0.92l0.96,-0.26l0.49,-0.92l0.81,-0.17l0.44,0.85l1.6,-0.25l1.54,0.48l1.23,-0.8l0.37,1.21l0.95,0.77l1.67,-0.08l0.72,0.37l0.74,-0.49l0.16,-1l1,-1.15l0.32,0.13l0.24,1.42l1.8,1.17l0.08,0.74l-0.56,0.49l1.33,1.06l2.19,0.12l0.32,-0.43l0.02,-0.99l0.86,-0.56l0.83,-1.36l1.4,-0.19l1.63,-0.74l0.99,0.26l0.51,0.96l0.57,-0.22l0.88,0.21l0.42,-0.47l-1.13,-2.21L996.22,475.53z"
},
{
"id":"RU-MUR",
"title":"Murmansk",
"d":"M88.41,405.96l0.64,-0.3l0.93,0.43l0.41,0.71l0.59,0.12l1.39,1.17l-0.09,0.7l1.12,0.36l0.26,-0.32l1.6,0.34l0.17,0.38l0.95,0.25l0.23,0.39l-0.18,1.66l-0.95,1.3l-0.77,0.38l-2.41,-0.74l-0.53,-0.59l-0.43,0.23l-1.34,-0.26l-0.22,-0.66l0.32,-0.54l-0.52,-1.17l-0.31,0.25l0.42,0.54l-0.33,1.09l-0.41,0.42l-0.62,0.06l0.69,0.65l-0.32,1.05l0.88,-0.94l0.92,0.55l1.06,0.15l0.23,0.25l-0.31,0.62l0.8,0.21l0.01,0.44l-0.71,0.27l-1.09,1.26l1.15,-0.4l0.2,-0.79l0.43,0.1l0.23,-0.45l0.07,0.28l0.32,-0.16l0.07,1.05l0.47,-0.83l0.98,0.01l0.56,0.26l-0.52,0.86l-0.06,0.8l0.73,-1.37l1.16,-0.17l-1.22,1.45l0.18,0.26l-0.72,1.54l0.53,-0.06l0.53,-1.39l2.15,-0.86l0.2,-0.38l1.42,0.64l-0.76,0.84l0.53,-0.16l0.09,0.32l-0.62,1.26l-1.02,-0.03l0.13,0.29l-0.35,0.34l2.15,0.11l-1.74,0.56l1.49,0.32l-0.01,1.04l-0.53,0.21l-0.45,0.85l-1.65,0.46l-0.55,0.48l0.78,-0.21l0.88,0.2l0.27,-0.46l1.07,-0.13l-0.06,-0.62l0.34,-0.18l0.58,-1.37l-0.15,-0.91l0.42,-0.54l-0.47,0.19l0.12,-0.87l1.2,-0.1l0.11,0.27l0.5,-0.38l0.54,0.17l0.36,-0.28l0.97,0.31l2.21,0.03l0.11,0.54l0.63,0.32l2.87,0.67l0.13,0.52l0.44,-0.41l1,0.23l0.29,0.43l0.34,-0.24l0.33,0.22l0.2,-0.3l-0.85,-0.96l0.97,0l0.54,0.48l0.96,0.02l2,0.92l0.27,-0.25l0.69,0.88l0.78,0.32l0.27,-0.24l0.28,0.51l1.33,0.27l0.47,1.23l0.15,-0.3l0.25,0.47l0.16,-0.16l1.04,0.5l3.16,2.85l1.22,0.63l0.29,0.62l0.49,0.16l0.07,0.44l0.5,-0.04l0.44,0.79l0.75,0.15l1,0.91l2.19,2.31l1.05,1.86l0.24,-0.09l1.17,1.13l1.45,2.09l0.37,0.11l0.44,-1.27l0.99,1.32l0.81,0.05l0.06,0.54l1.28,1.42l-0.05,0.4l0.64,-0.26l3.52,3.43l-0.25,-0.59l0.24,-0.24l0.52,0.48l0.84,-0.1l-0.66,-2.44l1.18,1.83l0.48,1.52l0.27,0.14l0.09,-0.25l0.86,1.09l1.69,1.03l-0.05,0.96l-0.48,-0.37l-0.27,0.24l0.96,1.51l0.29,-0.1l0.45,0.63l0.44,-0.6l-0.14,-0.59l0.41,-0.04l0.14,0.3l0.12,-0.36l0.9,1.44l0.86,-0.1l0.48,0.44l0.55,1.48l-0.47,1.33l0.24,0.88l-0.25,0.81l0.75,0.49l0.24,0.61l-0.27,2.76l0.4,0.62l0.82,0.45l0.46,-0.37l0.23,0.4l-0.35,1.01l0.63,0.54l-0.41,0.64l0.09,1.77l-0.59,0.06l0.25,0.59l-0.63,2.35l-3.52,4.36l-0.14,0.88l-0.69,0.36l-0.13,0.82l-0.78,0.95l-1.8,1.11l-1.6,1.73l-3.78,1.25l-2.58,1.55l-1.52,-0.08l-1.58,0.77l-2.57,0.17l-1.31,-0.46l-1.56,-0.11l-1.71,-0.54l-2.35,-1.57l-3.4,-1.42l-2.75,-0.13l-6.98,-1.78l-1.13,-0.57l-0.26,-0.86l-0.83,-0.02l-2.05,-2.17l-0.69,-0.24l-0.84,0.14l-0.64,0.76l-1,0.19l-0.61,-0.86l-0.01,-1.13l-2.5,-0.73l-0.61,0.12l-0.3,-0.2l-0.09,-0.66l-0.27,0.26l-0.34,-0.42l0.14,-0.44l-1.31,-0.72l-0.25,-0.78l-0.01,1.03l-0.33,-0.18l0.25,1.16l-0.69,0.37l-2.34,-1.94l-1.44,-1.43l-1.42,-2.15l-0.01,-0.72l1.24,-0.59l-1.44,0.23l-0.95,-0.78l-0.86,0.24l-0.52,-0.23l-0.55,-0.69l-0.59,0.5l-0.89,-0.21l-0.3,0.63l-1.3,-0.6l1.35,1.01l0.56,-0.26L89.8,461l0.72,0.29l0.58,0.5l-0.5,0.13l0.37,0.5l0.59,-0.02l0.73,0.42l0.26,1.95l-1.02,0.69l0.93,0l1.19,1.15l-0.05,0.36l0.68,0.6l-0.72,0.19l0.19,0.21l2.35,1.15l1.51,0.2l0.42,0.45l-0.1,0.46l-0.4,-0.45l-0.88,-0.16l-0.39,1.07l-1.67,-0.49l0.04,0.47l0,0l-1.91,-0.26l-0.29,0.21l-0.29,1.78l-1.56,0.17l1.19,1.04l-1.1,-0.39l0.2,0.94l-0.22,0.33l-3.13,-0.11l-0.8,-2.07l-1.02,-0.45l-0.13,-1.88l-1.64,-0.1l0.07,-0.35l-2.05,0.27l-2.85,-0.2l-1,0.36l-2.91,0.28l-2.43,-0.17l-2.69,0.63l0,0l-2.35,-4.31l-0.34,-2.49l3.59,-6.31l0.76,-0.55l0.01,-0.46l2.23,-2.98l0.55,-2.95l-2.45,-2.26l-2.5,-5.32l-4.92,-2.35l-1.5,-6.85l1.95,-3.73l0.58,-2.73l-2.24,-0.2l-0.41,-0.47l3.53,-2.98l0.78,0.81l0.73,-0.63l0.88,-1.43l0.37,-1.25l0.04,-2.44l1.33,-0.52l0.39,0.3l1.97,-2.14l1.12,0.11l0.89,-1.01l0.61,-1.93l-0.57,-2.22l0.56,-0.03l1.22,1.01l1.15,1.53l2.1,0.02l0.9,-0.91l-0.1,-2.07l-0.36,-0.44l0.12,-0.57l-0.39,-1.05l0.65,0.5l0.59,-0.32l0.19,0.36l0.45,-0.12l2.31,1.27l0,0.87l-1.23,1.83l0.5,-0.29l0.48,-0.98l0.46,-0.18l0.17,-0.81l1.68,0.27l0.64,0.45l0.02,-0.36l-0.84,-0.89l0.33,-2.14l0.33,-0.38l0.55,0.32l1.28,1.4l0.02,-0.45l0.37,0.08l-0.48,-1.29l-0.57,-0.57l0.29,-0.4l-0.64,-0.73l0.13,-0.8l0.53,0.05L88.41,405.96z"
},
{
"id":"RU-MO",
"title":"Mordovia",
"d":"M163.61,644.98L164.68,645.83L165.67,645.28L165.95,645.29L166.31,646L166.83,646.01L167.7,645.36L168.38,645.82L168.69,644.71L169.74,644.19L169.86,643.73L170.4,643.64L171.2,644.05L172,643.8L171.95,645L174.46,645.53L174.42,646.17L174.68,646.39L175.53,646.23L175.75,646.47L175.61,647.15L176.5,647.98L177.41,648.02L178.59,648.91L179.17,648.38L179.67,648.69L179.22,649.6L180.81,649.03L181.38,649.47L182.38,649.22L182.92,649.46L183.15,649.03L182.06,647.93L182.7,647.15L182.51,645.96L182.95,645.42L183.42,646.03L183.91,644.55L185.24,644.08L184.95,642.7L185.44,641.7L186.77,640.69L187.48,640.87L187.02,642.76L187.41,643.18L188.83,642.97L189.81,642.24L189.81,642.24L190,643.06L190.26,643.04L190.79,641.87L191.18,642.05L191.44,642.66L190.98,643.4L191.99,644.26L192.44,645.83L192.44,645.83L192.97,647.56L192.26,648.15L192.82,648.18L193.12,648.6L192.54,649.21L193.63,649.16L193.05,650.07L193.22,650.32L193.98,650.34L193.96,651.32L193.31,651.49L191.65,652.78L189.05,653.55L187.91,655.49L187.91,655.49L187.45,656.11L185.87,656.17L184.26,656.7L183.91,656.49L183.73,655.68L182.57,655.93L181.05,655.78L179.3,656.82L179.39,657.59L180.25,658.68L180.04,659.03L178.94,659.33L178.54,658.85L176.98,659.09L175.14,658.54L174.52,657.89L174.38,656.7L173.02,655.95L172.22,655.87L172.07,655.4L171.68,655.3L170.82,655.73L169.41,655.09L168.85,656.01L169.3,656.89L169,657.52L168.4,657.62L167.94,657.33L167.15,657.68L165.79,657.54L164.8,658.13L164.4,657.37L163.93,657.83L164.06,658.7L162.85,657.6L162.85,657.6L163.19,656.83L164.08,656.02L162.35,654.42L162.71,653.84L163.1,654.56L163.65,654.16L164.3,654.6L164.45,654.36L164.17,653.9L164.64,653.62L165.59,653.66L165.3,652.98L164.17,653.05L163.77,652.45L163.06,652.79L163.24,653.11L162.45,653.47L161.74,652.38L162.46,652.66L163.96,651.73L164.08,651.11L165.06,650.94L164.75,650.33L164.27,650.16L164.53,649.3L164.98,649.56L164.98,648.83L165.58,648.45L165.05,648.1L164.96,647.08L164.33,647.23L164.18,646.8L163.96,647.06L163.21,646.37L162.81,645.61L163.21,645.2L163.67,645.27z"
},
{
"id":"RU-MOS",
"title":"Moskva",
"d":"M111.25,631.17l1.36,-1.66l-0.41,-0.33l0.55,-0.75l-0.33,-0.65l1.36,-0.41l-0.27,-0.65l0.36,-1.01l-0.72,0.05l0.09,-0.97l0.53,0.35l0.23,-0.53l0.18,0.21l0.4,-0.3l0.08,0.28l0.34,-0.46l0.6,0.36l0.11,0.89l0.41,-0.23l1.63,0.41l0.29,0.47l0.39,-1l0.68,0.13l1.42,-1.07l0.67,0.16l0.15,-0.35l1.94,-0.98l-0.04,-0.27l1.45,0.66l0.73,-0.04l-0.08,-1.3l0.27,-0.4l-0.07,-0.63l-0.38,-0.37l0.89,-0.52l1.05,0.4l0.64,-0.46l0.4,0.19l0.53,-0.72l-0.04,-0.97l1.17,-0.61l1.33,1.05l0.67,0.15l0.51,1.35l1.64,-0.2l0,0l0.79,0.92l0,0l-0.59,0.14l0.41,1.53l-0.63,0.59l0.44,0.2l-0.25,0.24l0.27,0.51l0.41,-0.02l0,0.76l0.34,0.08l-0.34,1.62l0.53,0.77l0.37,-0.07l-0.19,0.41l0.35,1.43l0.48,0.66l-0.3,0.19l0.12,0.22l0.93,0.01l0.75,0.72l1.54,-0.25l-0.19,0.2l0.34,-0.08l-0.19,0.36l0.51,0.75l1.08,0.13l0.51,-0.29l-0.27,0.38l0.24,0.77l1.01,-0.03l0.11,0.38l0.28,-0.55l0.93,-0.06l0.6,-0.61l1.09,0.12l0.16,1.23l1.2,0.99l-0.25,1.7l0.79,-0.01l0.23,0.37l-0.38,0.98l0.56,1.11l0,0l-0.31,0.04l-0.23,0.78l-1.15,0.74l-1.41,0.18l-0.49,0.89l0.61,-0.22l0.34,0.3l-0.39,1.31l-0.25,-0.19l-0.63,0.24l-0.47,-0.27l-0.14,0.58l-0.46,0.02l-0.59,0.63l0.08,0.39l-0.54,0.51l0.08,0.47l-0.58,0.82l0.35,0.09l-0.96,0.51l-0.02,0.82l-0.52,-0.2l-0.3,0.33l-0.72,-0.02l-0.22,0.35l-0.41,-0.32l-0.72,0.26l-0.2,0.81l0.37,0.14l-0.4,0.72l1.26,0.52l0.05,0.45l-0.37,0.11l-0.14,0.49l-0.6,-0.43l-0.22,0.56l-0.51,-0.15l-0.06,1.01l-0.35,0.18l0,0l-1.34,-0.6l-0.14,-0.48l0.35,-0.37l-0.6,-0.63l-0.4,-1.48l0.66,-0.13l0.26,-0.81l-0.19,-0.43l-0.52,0.16l-0.73,-0.36l-0.35,0.35l-0.92,-0.92l-0.54,-0.14l0.08,-0.48l-0.78,-1.13l-1.2,0.24l0,1.08l-0.57,0.39l-0.66,-0.29l-0.4,0.18l-0.16,-0.78l-0.49,-0.56l-1.04,-0.14l-0.03,0.23l-0.66,-0.31l0,0l-0.24,-0.2l0.04,-1.23l-0.66,-1.12l0.27,-0.11l-0.01,-0.43l-0.47,-0.2l0.02,-0.38l0.3,-0.1l0,0l0.11,-0.01l0,0l0.43,-0.22l-0.06,-0.83l0.36,-0.27l0.4,0.15l0.01,-0.23l0.32,0.47l0.63,-0.38l-0.17,-0.83l0.32,0.02l-0.16,-0.27l0.47,-0.67l-0.69,-0.69l0.15,-0.3l0.37,-0.17l0.65,0.57l0.06,-0.45l0.48,-0.22l-0.23,-0.4l0.14,-0.66l0.97,-0.21l0.95,-1.41l0.3,-0.09l0.1,0.4l0.35,0.04l0.03,-0.5l-0.92,-0.47l-0.04,-1.01l-1.05,-0.9l-0.96,-0.16l0.12,-0.58l-0.4,0.17l0.12,0.44l-0.78,0.4l-0.27,-0.45l0.22,-0.49l-0.6,-0.04l0.53,1.06l-0.57,0.33l0.15,0.32l0.29,-0.11l-0.19,0.51l-0.42,-0.09l0.09,0.39l0.36,-0.28l0.16,1.15l-0.2,-0.13l-0.24,0.35l0.51,-0.22l0.1,0.43l-0.69,0l-0.66,0.56l-0.95,0.25l0.32,1.6l-0.34,0.12l0.41,0.33l-0.64,-0.3l-0.62,0.1l-0.28,-0.75l-0.86,0.12l-0.08,0.86l0.39,0.75l1.22,1.17l-0.52,0.26l-0.03,0.39l0,0l-0.01,0.01l0,0l-1.19,0.46l-0.18,-0.6l-1.1,-0.04l-0.23,-1.04l-0.42,0.47l-0.89,-0.02l-0.1,0.59l-0.26,-0.02l-0.54,1.09l-0.15,-0.25l-0.75,0.22l-0.26,-0.39l-0.61,0.08l-0.45,-0.5l-0.83,0.09l-0.7,-0.75l-0.92,0.11l-0.84,0.77l-0.76,-0.04l-0.34,-0.42l0,0l-0.65,-0.73l0.39,-1.34l-0.16,-1.82l0.67,-0.22l-0.04,-0.42l-0.47,-0.52l0.04,-1.62l-0.34,-0.08L111.25,631.17zM126.15,631.11l-0.4,-0.22l-0.11,-0.66l0.42,-0.07l0.56,0.5l-0.4,0.09L126.15,631.11zM127.69,630.54l0.23,0.13l0,0l-0.62,0.31l0.22,-0.31l0,0L127.69,630.54zM124.56,633.66l0.44,0.4l0.55,-0.18l-0.17,-0.14l0.19,0.29l-0.86,0.21l-0.31,-0.28l0.31,-0.16l-0.42,0.11l-0.03,-0.29l-0.4,0.29l0.71,-0.3l0,0L124.56,633.66zM130.77,632.8l0.38,-0.05l0,0l-0.31,0.13l0,0L130.77,632.8zM124.42,640.44L124.42,640.44L124.42,640.44L124.42,640.44L124.42,640.44L124.42,640.44zM124.46,640.53L124.46,640.53L124.46,640.53l0.01,-0.02l0,0L124.46,640.53zM125.19,641.3l-0.14,0.05l0,0L125.19,641.3L125.19,641.3L125.19,641.3z"
},
{
"id":"RU-NGR",
"title":"Novgorod",
"d":"M73.75,597.99L74.52,598.28L75.39,597.67L75.41,596.54L75.05,595.56L75.47,594.88L75.2,594.42L75.42,594.02L75.63,593.87L77.03,594.73L78.24,594L79.09,594.29L79.5,594.13L79.8,592.68L81.12,591.58L81.79,589.74L82.57,589.76L83.41,590.36L84.35,589.99L85.22,588.6L85.23,587.85L85.76,587.46L85.37,585.52L86.38,585.62L87.07,586.49L87.44,586.53L87.81,586.42L88.16,584.97L88.53,584.87L90.9,586.53L91.22,588.11L93.4,589.42L94.07,589.16L94.51,588.36L94.22,587.45L94.42,586.61L95.59,585.67L96.26,584.6L96.69,585.3L98.23,586.37L98.96,585.48L99.61,585.72L100.75,585.44L102.19,588L102.83,588.1L103.51,588.68L104.02,588.85L104.37,588.24L105.55,588.05L107.58,589.07L108.69,589.01L108.69,589.01L110.15,589.73L109.73,590.06L110.04,590.33L111.83,590.87L111.56,592.84L112.21,592.44L112.35,593.47L113.3,592.11L113.92,592.12L115.19,592.86L115.58,592.65L116.09,593.33L118.26,594.17L118.75,594.78L118.82,595.46L119.3,595.81L119.36,596.41L119.73,596.75L120.68,596.87L120.68,596.87L120.19,597.32L119.32,597.1L118.87,597.58L118.49,597.35L117.97,597.96L117.33,597.7L117.15,598.57L114.51,598.08L112.78,598.95L112.5,599.29L112.81,599.93L111.83,601.15L111.09,601.29L110.8,601.64L110.12,601.1L109.79,601.28L109.05,600.88L108.46,601.48L108.42,602.21L108.73,602.74L108.27,603.22L106.77,602.33L106.25,602.49L105.94,602.02L105.33,602.02L104.66,601.4L103.81,601.53L103.74,601.19L102.58,602.46L101.26,602.25L100.08,603.84L101.21,604.78L101.03,605.96L100.22,606.54L100.02,607.25L100.35,607.94L99.86,608.4L99.25,608.15L98.33,608.48L98.62,608.84L98.34,609.44L98.56,610.01L97.96,610.19L97.77,610.7L97.75,611.21L98.31,611.6L98.1,612.28L97.35,611.38L96.45,612L95.91,611.5L95.58,611.9L95.1,611.6L94.75,611.75L93.74,613.44L92.96,613.41L92.54,614.04L91.89,614.02L91.84,614.39L90.94,614.29L90.85,615.35L90.17,615.21L89.96,615.59L89.17,615.81L89.22,616.25L88.86,616.31L89.03,616.78L88.73,616.9L88.44,616.19L87.92,616.3L87.67,616.73L87.28,616.52L86.72,617.33L87.03,617.69L86.54,617.82L86.14,618.75L83.66,618.35L83.21,618.84L81.53,618.07L81.53,618.07L81.19,617.89L80.31,618.38L79.59,617.9L79.3,617.17L80.33,614.56L77.71,612.75L78.17,611.5L77.91,611.24L79.39,609.57L78.7,609.55L77.91,608.98L78.39,607.73L77.75,607.39L78.33,606.6L78.38,605.75L76.48,605.72L75.18,605.08L74.43,605.08L74.35,604.35L73.35,603.44L72.08,603.05L72.29,602.09L71.9,601.45L73.75,600.09z"
},
{
"id":"RU-NEN",
"title":"Nenets",
"d":"M228.26,435.51l-1.2,0.39l-1.03,-0.09l-0.55,0.37l-0.84,-0.08l-0.07,0.44l-1.1,0.55l1.15,-1.37l1.06,-0.67l3.05,0.16L228.26,435.51zM280.79,418.13l2.2,0.99l0.9,0.72l0.32,0.5l-0.02,0.41l-0.25,0.03l0.42,0.49l0.22,1.48l-0.56,-0.26l-0.54,-2.29l-1.35,-0.97l-0.85,-0.18l-0.99,-0.92l-0.06,-1.02L280.79,418.13zM215.72,417.35l1.83,1.31l-0.38,0l0.22,0.43l0.37,-0.32l0.99,0.95l0.83,1.51l0.18,1.81l-1.13,2.21l-0.17,-0.74l1.07,-3l-0.24,-0.7l-0.01,0.98l-1.18,1.03l0.09,0.55l-1.53,0.92l0.24,0.06l-0.37,0.44l0.1,0.31l0.3,-0.05l-0.82,0.89l-0.88,1.85l-2.12,1.14l-0.31,-0.22l0.08,0.38l-2.73,1.14l-0.04,-0.25l-1.52,0.57l-0.26,-0.61l-0.17,0.83l-1.17,-0.57l0.5,0.16l-2.2,-2.35l0.43,-0.08l-0.45,-0.43l-0.1,0.32l-0.2,-0.15l0.2,1.26l1.11,1.41l-0.47,-0.28l-0.66,-0.68l-0.21,-0.98l-0.03,-5.25l0.45,-2.63l0.97,-2.59l1.84,-2.05l1.21,-0.76l2.64,-0.46l1.38,0.66L215.72,417.35zM192.99,466.3l-0.02,0.24l2.35,-0.54l0.28,0.46l0.19,-0.58l0.82,-0.04l2.36,-1.27l1.52,0.67l-0.17,-0.59l1.18,-1.7l0.09,-2.39l-0.58,-0.98l0.79,-0.88l-0.1,-1.78l1.11,-1.92l-0.64,-2.42l1.17,-1.25l0.77,0.49l-0.25,0.07l0.1,0.45l1.15,-1.26l0.68,-0.27l0.91,0.51l1.5,-1.09l0.23,0.15l-0.23,0.26l1.34,-0.15l1.1,0.68l-0.46,0.22l0.2,0.39l0.56,-0.11l-0.42,-0.1l0.35,-0.46l-1.42,-1.27l-0.82,0.3l0.34,-1.28l-0.11,-1.25l-1.23,-1.55l1.72,1.41l1.2,0.14l1.12,-0.35l2.95,-1.91l3.39,-2.81l-0.16,0.7l-1.5,1.03l0.37,0.35l0.51,-0.26l-0.03,-0.32l0.42,0.01l-0.05,-0.5l0.42,-0.13l0.34,-0.67l-0.14,-0.37l5.16,-5l0.8,0.5l2.75,-0.76l0.51,-0.55l0.48,0.03l0.07,-0.39l0.96,0.12l0.3,-0.41l-0.66,-0.1l0.48,-0.73l2.13,-0.45l2.4,-1.23l0.33,0.15l-0.74,1.02l-0.77,0.06l0.07,0.74l0.65,-0.72l0.63,0.4l-0.04,0.62l0.4,-0.3l0.29,0.13l-0.22,0.11l0.08,0.87l-0.76,0.49l-0.21,0.54l1.06,1.01l0.12,-0.32l0.67,-0.09l1.3,-1.37l0.72,-0.36l0.42,-1.11l-1.29,-0.87l-0.25,-0.87l-0.44,-0.23l0.27,-0.91l-0.9,0.98l-0.81,-0.39l7.7,-5.75l3.69,-1.53l4.08,-0.65l0.98,0.32l-0.45,0.31l-0.62,-0.25l-0.64,0.48l-3.27,0.8l-1.93,0.2l0.25,0.25l-0.48,0.38l1.01,0.75l0.13,-0.25l-0.51,-0.47l1.01,0.08l1.43,0.7l-0.28,0.75l-0.62,0.03l-0.32,1.11l0.11,0.88l-0.77,0.8l-0.27,1.02l0.62,0.31l0.85,1.3l0.26,2.23l-0.92,0.68l0.08,0.67l-0.49,-0.2l-0.57,-0.84l-0.47,0.14l-0.24,-0.31l0.03,0.3l0.49,0.21l-0.02,0.91l-0.35,-0.66l-0.9,-0.33l-1.16,0.62l-0.82,1.28l-0.01,1.02l-0.38,-0.03l0.23,1.51l-0.47,0.15l0.23,0.13l0.6,-0.53l-0.08,-0.65l0.39,-0.69l1.14,-0.35l0.83,0.17l1.13,-0.36l0.43,0.33l0.29,-0.12l0.4,0.27l-0.24,0.36l0.3,0.38l0.92,-0.66l-0.42,0.76l0.57,-0.82l0.09,0.45l0.48,-0.6l-0.14,0.98l0.28,1.38l-1.24,2.15l0.28,0.18l1.4,-1.99l0.43,-2.5l0.64,-0.12l1.15,-1.29l0.41,0.17l0.87,2.23l0.47,0.4l0.82,-0.01l-0.23,0.79l0.58,-1.08l-0.09,-0.81l0.53,-0.71l-0.7,-1.4l0.3,0.19l-0.21,-0.3l0.97,-2.03l0.5,0l-0.06,-0.29l0.88,-0.88l0.25,0.13l-0.08,-0.23l1.04,-1.02l2.06,-0.02l2.12,-1.83l0.8,-0.12l1.47,1.09l1.22,0.01l1.29,-0.58l1.06,0.42l0.67,0.87l1.35,0.68l1.91,-0.23l1.11,-1.14l0.03,-0.9l1.29,-1.97l-0.68,-0.21l-1.34,0.72l-1.22,-0.04l5.11,-1.77l0.23,0.17l-0.33,0.48l0.2,0.79l0.54,-0.42l0.14,-0.53l-0.47,-0.4l0.18,-0.3l6.59,-3.37l2.12,-0.07l0.77,0.28l-0.04,0.25l-0.56,-0.23l-0.89,0.36l-0.8,0.78l0.91,0.29l2.1,1.74l0.79,1.61l-0.57,1.26l-1.29,-0.22l-0.61,0.32l-0.04,0.81l-0.67,0.91l0.58,1.29l-0.3,1.94l0.37,0.43l1.47,0.27l1.11,0.71l1.77,-0.52l0.23,-0.48l0.56,-0.05l0.47,-1.08l-1.09,-3.56l0.98,-1.58l0.84,0.74l2.72,-0.34l1.35,-1.08l1.27,-2.35l0.59,-0.5l0.66,0.05l-0.17,0.74l1.15,0.01l0.48,1.11l0.4,-0.02l-0.32,-0.13l0.05,-1.09l-1.56,-1.39l-0.12,0.29l-0.14,-0.19l0.35,-1.47l-0.32,-1.12l0.15,-0.4l-0.69,-1.46l-0.43,-0.39l-0.31,0.17l0.09,1.12l-0.85,-0.57l-0.15,-2.66l-2.35,-3.85l-0.09,-0.65l-0.55,-0.5l0.1,-0.71l-0.36,-0.4l0.24,-1.44l0.92,-0.83l0.74,0.27l1.45,-0.13l-0.09,0.75l0.85,0.28l0.25,-0.29l-0.77,-1.6l0.05,-0.54l0.63,0.17l-0.41,-1.91l0.96,-1.09l1.46,0.64l0.39,-0.74l0.54,0.99l0.82,-0.05l0.36,0.65l0.95,0.27l1.76,0.11l2.23,0.7l5.7,0.45l1.05,0.34l0.01,0.67l0.11,-0.7l4.04,1.56l5.89,2.98l0.89,0.97l-0.2,0.29l0.33,-0.19l2.37,2.06l0.62,1.32l0,0l-0.81,0.8l-0.45,1.15l0.19,1.71l-0.27,0.56l-1.13,0.79l0.6,1.55l-0.27,0.56l0.89,0.74l0.26,-0.72l0.55,0.27l1.68,1.61l1.37,-0.17l0.97,0.61l-0.01,0.89l1.25,0.7l-0.33,1.06l1,2.35l-0.26,1.02l-1.35,1.36l0,0l-1.2,0.72l-0.66,-0.04l-1.18,-0.72l-0.77,0.34l-1.35,0.02l-1.31,1.12l0.19,2.68l-1.04,0.42l-0.28,0.79l-3.53,2.05l0.4,2.12l-1.79,2.15l0.08,0.98l-1.51,-0.72l-1.15,0.34l-1.79,1.82l-1.18,2.57l-0.17,2.53l-8.03,5.62l-0.86,1.53l-1.12,-0.18l-1.19,0.72l-0.8,-0.27l-38.01,0.43l-9.87,-0.28l-17.42,-1.53l-3.75,3.03l-0.8,0.08l0.16,2.32l-18.81,12.03l0,0l-1.91,-0.38l-1.35,0.13l-1.02,-0.34l-1.62,0.13l-2.37,2.12l-0.71,1.27l0.88,1.48l-0.37,0.34l-2.39,-0.22l-2,0.28l-5.21,-4.21l-1.89,0.8l-2.09,-1.53l-1.26,0.55l-0.54,-0.08l-2.96,-2.15l-3.98,-1.13l-1.3,-1.82l-1.72,-0.44l0,0l0.62,-1.41l0.5,-0.23l0.52,-2.59l1.05,-0.31l-0.74,-0.22l-0.93,-2.08l0.91,-0.78l-0.12,-1.22l0.41,-0.23l-0.93,-1.75l-0.72,-0.67l0.09,-0.55l0.51,-0.41l-0.74,0.38l-0.79,-0.89l0.04,-0.45l-1.01,-0.43l-1.28,0.15l-0.61,-0.71l0.02,-1.19l1.28,-5.22l0.95,-2.22l0.35,-0.15l-0.1,0.63l0.37,-0.75l0.23,0.05l-0.42,-0.42l-0.26,0.1l0.51,-1.58l-0.48,-1.36l0.4,-0.75l0.56,0.01l-0.33,-0.44l0.78,-0.24l-0.73,-0.19l-0.24,0.2l0.04,-1.12l1.34,-1.16l-1.06,0.23l0.13,-3.66l-0.28,-1.77l-1.32,-1.64l-4.42,-3.81l-0.98,-1.21l-0.01,-0.55l1.35,-0.01l4.22,2.64l4.78,-0.05l3.71,0.32l2.3,0.52l3.42,1.6l-0.83,-0.38l-0.23,0.36l1.07,1.44l0.02,0.66l0.82,0.49l1.31,1.98l1.54,1.16l0.07,0.33l-0.52,0.2l0.43,-0.12l0.14,1.68l0.97,2.05l-0.06,1.72l-1.84,0.03l-1.06,-0.36l0.18,0.32l-1.71,0.57l-0.68,-0.12l-0.77,0.69l-1.31,0.21l-0.1,-0.35l-1.03,0.28l-1.36,1.04l-0.3,-0.13l-0.17,0.38l0.39,-0.08l0.18,0.48l-0.29,1.56l-0.31,-0.17l-0.72,0.32l-1.15,1.33l-0.52,1.28l-0.12,1.7l-0.56,0.4l0.27,-0.28l0.37,0.41l0.2,-0.17l1.52,1.28l3.13,1.71l-0.1,1.71l0.72,0.65l0.87,2.49l1.46,0.79l0.11,0.28l-0.42,0.39l3.81,-1.03l0.42,0.03l0.3,0.43L192.99,466.3zM282.75,394.56l-0.03,0.78l0.67,0.3l1.44,1.47l1.71,2.99l1.45,1.26l-0.02,0.5l1.23,0.78l0.52,-0.14l-0.03,0.51l0.47,0.67l1.66,1.94l0.77,0.3l0.06,0.96l0.7,1.71l-0.56,0.92l0.15,0.94l-0.85,-0.52l0.28,0.67l-0.68,0.03l-0.17,0.33l-0.35,-0.23l0.15,0.4l-0.63,-0.25l0.19,0.43l-1.41,-1l0.24,0.67l-0.56,-0.18l0.2,0.77l-0.45,-0.17l-0.17,-0.56l-0.8,0.14l-1.51,-0.51l0.23,-0.62l-0.28,-0.31l0.07,-0.74l0.22,0.34l0.7,-0.13l-1.12,-1.61l-0.93,-0.7l-0.09,0.24l-0.73,-0.31l-0.39,0.19l-0.35,-0.49l-0.61,-0.02l-1.04,-0.72l1.39,1.88l-0.82,-0.02l-0.55,-1.27l-1.3,-1.07l-1.46,-2.11l0.32,-0.79l-0.71,-0.27l0.77,-0.24l-0.52,-0.4l0.33,-0.16l-0.08,-0.34l-0.36,0.33l-0.17,-0.62l-0.19,0.25l-0.27,-0.18l0.66,-0.45l-0.62,-0.54l-0.17,0.26l0.04,-0.41l-0.41,-0.02l0.08,-0.39l1.39,0.28l1.04,0.85l0.48,-0.09l0.01,-0.59l-2.02,-1.64l-0.17,-0.54l0.97,0.43v-0.55l0.95,-0.64l0.1,-1.13l0.96,-0.07L282.75,394.56z"
},
{
"id":"RU-SE",
"title":"North Ossetia",
"d":"M177.7,767.38L178.03,767.6L179.76,767.09L180.74,767.25L181.54,768.24L181.54,768.24L181.31,769.3L181.31,769.3L180.6,768.92L180.33,769.89L179.93,769.82L179.75,769.28L178.94,769.39L178.84,770.66L179.4,771.17L179.27,772.78L180.04,772.81L181.32,774.13L181.69,775.68L180.76,776.62L180.04,776.46L179.78,775.96L179.51,777.02L179.51,777.02L178.29,776.98L176.97,777.36L176.15,778.2L174.9,778.41L174.28,778.86L173.01,778.58L172.73,778.19L173.16,777L172.11,776.51L171.51,775.87L170.48,775.58L170.48,775.58L170.97,775.16L171.54,775.52L172.19,775.23L174.18,771.97L174.57,772.57L175.04,772.33L175.31,772.67L174.95,772.72L175.1,772.96L175.47,773.03L175.85,772.59L175.69,771.55L175.97,771.23L176.69,771.57L177.41,771.07L178.07,771.35L178.28,771.16L178.47,768.93L177.63,768.14z"
},
{
"id":"RU-NVS",
"title":"Novosibirsk",
"d":"M404.86,614.27L407.17,614.84L409,614.64L410.51,615.25L418.58,615.48L421.05,615.28L421.95,616.27L427.72,617.54L429.06,618.58L430.88,619.46L434.69,624.87L437.02,624.57L441.01,623.52L441.44,623.69L443.86,626.92L444.39,627.08L449.89,625.53L452.73,625.24L453.16,624.71L453.14,624.04L455.09,623.52L455.96,625.17L454.86,627.19L455.62,627.83L455.52,628.81L456.25,629.28L456.18,630.31L456.84,632.29L456.28,633.54L455.8,633.74L456.31,634.42L458.64,634.45L460.03,631.9L461.26,630.39L462.51,629.98L463.45,630.71L464.06,630.64L464.77,630.01L464.77,630.01L465.42,630.2L465.6,631.39L465.28,631.83L465.73,633.27L465.55,633.64L466.21,634.78L467.06,635.15L467.32,635.76L467.12,637.33L466.06,638.15L467.8,638.21L467.74,639.9L468.15,641.53L467.77,643.08L468.92,644.4L469.21,645.39L468.87,645.91L468.32,646.09L468.18,646.73L469.01,647.51L468.46,648.28L469.26,650.25L469.26,650.25L469.22,650.54L467.96,650.79L465.89,651.79L464.48,653.57L464.18,653.2L463.19,652.93L461.14,653.99L460.06,653.8L457.78,654.15L457.88,655.19L457.22,655.92L456.65,655.69L456.37,654.81L455.43,654.71L454.81,655.04L452.17,657.63L452.3,658.31L451.67,659.17L451.81,659.65L450.91,660.54L451.13,660.83L450.38,661.1L449.67,660.95L448.26,659.92L448.48,659.31L448.1,659.11L445.59,658.57L445.1,657.3L445.84,656.82L445.91,656.18L444.03,656.13L444,655L443.17,654.16L441.97,654.2L441.47,653.7L440.76,653.81L440.53,652.85L439.6,651.93L439.34,650.8L438.94,650.76L438.4,651.34L438.67,652.17L436.94,652.69L436.44,653.17L436.59,653.73L435.74,653.82L434.55,654.78L434.13,654.91L433.84,654.37L433.51,654.51L433.07,654.84L433.27,655.34L431.69,656.31L431.51,657.06L429.93,657.56L429.79,658.15L428.94,658.76L428.25,659.05L427.52,658.64L426.93,659.12L426.26,659.22L425.83,658.91L425.6,659.36L425.1,659.06L423.42,659.39L423.04,659.67L422.69,660.93L420.54,661.47L419.73,660.83L419.69,659.94L419.17,660.51L418.14,660.57L418.16,661.43L418.9,661.87L418.17,662.06L418.3,662.61L418.15,662.93L417.85,662.81L417.53,663.59L417.53,663.59L409.58,656.81L407.75,654.77L407.17,653.17L408.48,653.26L408.81,653.68L409.48,653.26L410.15,652.36L410.36,651.44L410.21,650.77L409.72,650.6L410.81,650.01L410.77,649.62L409.39,650.12L408.79,650.99L407.38,651.25L405.79,650.87L405.74,651.87L401.95,653.62L401.95,653.62L401.74,649.6L401.86,648.71L402.8,648.06L402.63,647.04L401.96,646.68L401.74,645.61L401.11,644.94L400.93,645.61L400.47,644.25L399.11,644.24L399.72,642.56L399.17,641.65L398.65,641.62L398.96,640.48L398.31,639.54L398.22,638.75L397.66,638.6L398.74,637.09L399.41,636.87L398.07,636.13L397.86,635.41L398.16,635.04L397.55,634.09L397.86,633.7L398.76,633.98L399.26,633.73L399.02,632.2L400.37,630.66L400.27,629.92L401.35,629.73L401.88,629.1L402.83,629.12L404.15,628.33L405.42,628.64L406.25,628.17L406.1,627.49L404.86,626.39L404.74,625.27L405.02,624.7L404.38,624.18L403.16,625L402.78,624.29L404.28,622.5L404.96,622.35L405.84,621.38L405.84,618.45L405.35,617.85L405.4,616.73z"
},
{
"id":"RU-NIZ",
"title":"Nizhegorod",
"d":"M191.8,602.9L191.91,603.6L192.77,603.25L196.79,603.51L198.89,603.75L201.75,604.72L200.48,606.17L200.09,609.04L199.55,610.1L199.11,610.3L197.97,609.53L196.35,610.58L194.99,610.32L194.6,610.57L194.07,611.7L194.2,613.11L195.01,614.46L194.32,615.04L194.71,615.66L194.45,617.83L194.45,617.83L194.05,617.33L193.67,617.99L193.11,618.14L191.61,617.65L190.94,618.5L188.79,618.96L188.23,619.71L188.35,622L187.31,621.94L186.64,622.71L186.35,623.86L186.54,624.42L187.46,624.23L188.72,625.06L188.79,625.89L188.08,626.81L189.71,628.01L189.63,628.72L190.09,629.99L190.09,629.99L189.67,630.88L189.85,632.6L188.83,633.97L188.84,634.8L190.29,636.18L191.83,636.84L192.02,637.6L191.05,638.26L190.76,639.39L189.83,639.95L189.4,640.64L189.81,642.24L189.81,642.24L188.83,642.97L187.41,643.18L187.02,642.76L187.48,640.87L186.77,640.69L185.44,641.7L184.95,642.7L185.24,644.08L183.91,644.55L183.42,646.03L182.95,645.42L182.51,645.96L182.7,647.15L182.06,647.93L183.15,649.03L182.92,649.46L182.38,649.22L181.38,649.47L180.81,649.03L179.22,649.6L179.67,648.69L179.17,648.38L178.59,648.91L177.41,648.02L176.5,647.98L175.61,647.15L175.75,646.47L175.53,646.23L174.68,646.39L174.42,646.17L174.46,645.53L171.95,645L172,643.8L171.2,644.05L170.4,643.64L169.86,643.73L169.74,644.19L168.69,644.71L168.38,645.82L167.7,645.36L166.83,646.01L166.31,646L165.95,645.29L165.67,645.28L164.68,645.83L163.61,644.98L163.61,644.98L163.57,643.63L164.02,643.26L163.56,642.89L163.2,643.2L162.91,642.96L161.92,643.61L160.3,643.22L160.46,641.94L159.37,642.58L158.81,641.93L158.91,641.45L158.91,641.45L159.42,641.25L159.86,640.38L160.17,638.71L160.52,638.71L161.29,637.77L160.91,636.65L160.95,635.25L162.2,633.54L163.36,632.91L163.7,631.42L164.5,631.29L165.27,630.56L165.36,629.92L165.1,629.6L165.46,629.16L166.3,628.97L166.96,628.22L167.01,627.69L165.65,627.14L165.44,625.72L164.76,625.06L164.76,625.06L165.18,624.25L166.86,624.18L166.81,621.7L166.41,622.01L166.06,621.72L166.44,620.83L166.06,620.33L166.49,619.75L167.29,619.43L167.86,619.75L168.34,619.52L168.37,619.18L171.18,618.84L172.41,616.5L171.91,616.28L171.96,616.02L171.06,615.8L171.13,614.58L171.48,614.04L172.34,613.64L172.15,613.2L172.65,612.84L173.09,613.16L173.29,612.59L173.63,612.82L173.74,612.52L172.6,611.84L172.71,611.37L172.71,611.37L175.22,611.47L176.56,610.51L177.45,610.46L179.04,607.98L180.08,608.1L180.23,607.17L180.73,606.83L180.57,606.16L180.95,605.77L180.69,603.55L181.02,603.08L183.43,602.96L184.29,603.76L185.17,603.52L186.35,605.03L186.84,605.05L187.25,604.69L187.5,603.72L187.81,603.76L188.03,603.38L188.55,603.52z"
},
{
"id":"RU-ORE",
"title":"Orenburg",
"d":"M236.03,650.49L236.38,650.92L237.74,650.89L239.16,651.66L239.82,651.12L240.29,651.77L240.19,652.07L239,652.43L238.89,652.92L239.65,653.36L239.53,654.19L240.9,653.57L241.78,654.6L242,654.51L242,654.51L242.71,655.32L243.73,657.49L245.04,658.86L246.72,661.46L247.89,662.45L248.69,662.36L250,662.96L250.83,664.38L252.46,664.03L252.8,664.31L253.3,666.8L254.12,668.06L254.15,668.8L254.71,669.18L255.93,668.8L256.11,670.02L256.39,670.24L256.03,670.62L255.44,670.47L255.19,671.05L255.51,671.4L256.05,671.26L256.8,671.89L257.31,674.01L259.32,674.61L260.94,672.41L261.25,671.14L262.92,672.29L263.43,671.91L263.65,672.13L263.24,672.92L263.82,673.69L263.97,674.88L263.69,675.69L262.51,676.85L263.21,677.58L263.75,676.68L264.06,676.67L265.39,678.02L266.18,679.71L265.52,680.7L266.78,682.73L266.5,683.81L267.15,683.92L267.54,683.4L267.18,682.22L267.57,681.98L268.55,682.6L269.68,684.07L270.9,683.28L271,682.29L272.17,682.62L273.02,680.82L273.46,680.72L273.77,681.08L274.42,680.98L275.97,681.42L276.68,682.34L277.09,682.41L278.21,681.77L279.2,681.65L279.78,681.03L280.58,678.1L279.95,677.43L280.22,675.92L280.67,675.6L281.26,675.78L281.7,675.16L281.17,673.88L281.28,673.54L281.28,673.54L282.31,673.52L282.89,674.65L284.29,675.48L284.04,674.39L284.27,673.76L285.67,673.17L285.99,673.12L286.22,673.59L287.1,673.31L287.95,673.73L288.21,673.51L289.17,674.17L290.69,674L291.06,675.77L290.04,676.66L289.27,678.37L290.22,679.03L290.22,679.03L289.85,679.11L289.76,679.54L290.11,680.36L290.7,680.56L290.68,680.12L292.28,681.16L293.11,681.33L292.19,682.49L292.79,683.1L293.68,683.45L295.98,683.5L296.05,684.27L296.57,685.17L297.85,685.27L299.07,685.92L300.02,685.6L300.52,686.6L301.4,687.47L300.76,687.68L299.62,692.82L295.32,694.32L292.8,694.22L291.65,693.96L290.78,692.87L290.69,692.25L289.88,692.01L289.41,692.43L288.18,695.19L286.02,695.97L286.09,694.96L285.64,694.34L284.22,694.47L283.78,694.15L281.56,693.9L280.69,693.08L280.63,692.36L279.34,692.45L279.1,691.16L279.38,690.37L279.1,689.79L277.71,689.59L277.14,688.66L276.58,688.98L276.34,689.71L275.8,689.58L275.68,689.05L275.05,689.54L274.52,689.14L274.13,689.32L273.74,688.9L273.28,689.01L273.12,691.27L272.76,691.5L272.51,691.11L271.94,691.22L271.53,691.87L270.38,691.29L269.19,689.4L268.04,689.9L267.57,689.63L267.18,689.88L266.67,689.55L265.93,689.59L265.95,690.81L265.27,690.6L264.27,689.48L264.03,689.75L264.1,690.76L263.53,690.83L263.22,691.52L262.06,691.25L261.66,693.2L258.8,694.91L258.5,695.37L257.01,694.21L256.08,694.34L254.23,692.71L253.97,692.38L254.27,691.55L253.9,691.26L252.66,692.32L252.27,691.81L251.43,691.69L251.06,692.63L251.57,694.69L250.72,695.69L250,695.69L249.39,694.64L250.04,692.21L248.49,691.79L247.66,690.53L247.73,690.03L247.52,689.73L247.38,689.88L247.36,689.23L246.6,688.63L244.05,687.9L243.55,686.99L243.74,686.05L241.91,684.61L241.21,684.92L241.09,684.68L239.75,684.76L239.09,685.12L238.7,684.79L238.29,685.06L238.46,684.74L237.64,684.67L236.94,685.01L236.99,685.24L235.97,685.18L234.37,681.71L233.89,682.27L233.26,682.25L232.79,682.97L231,682.66L230.27,683.73L230.55,684.51L229.65,685.07L229.35,685.11L229.48,684.61L228.91,684.07L228.57,684.65L227.92,684.97L227.1,684.89L226.58,684.13L227.43,683.96L227.42,683.01L226.76,682.59L225.29,682.84L224.06,682.7L223.68,681.93L223.68,681.93L223.87,681.37L223.87,681.37L226.16,679.67L227.75,678.06L228.08,677.48L227.62,675.32L228.94,673.8L228.94,673.35L228.3,672.67L228.75,671.36L229.26,670.84L229.76,671.03L230.28,669.67L230.16,668.86L231.66,667.44L232.76,666.82L233.11,665.62L232.64,665L233.26,663.51L233.15,662.98L234.19,662.54L233.19,662.21L232.73,661.12L233.54,659.92L233.82,658.2L234.79,656.69L235.22,655.07L235.25,654.42L234.41,653.54L234.34,652.98L234.69,652.85L234.9,651.15z"
},
{
"id":"RU-ORL",
"title":"Orel",
"d":"M117.27,659.6L117.58,660.39L117.98,660.27L119.34,660.88L119.74,661.73L120.88,662.58L122.21,662.35L122.05,662.57L122.67,663.6L123.98,663.98L124.3,663.68L125.89,664.4L126.56,664.16L126.6,663.61L128.62,663.93L128.63,665.55L129.22,665.97L129.62,665.56L130.61,667.04L130.61,667.04L130.38,667.92L130.79,668.42L130.5,669.26L130.82,669.97L130.02,671.46L129.46,671.48L129.5,671.91L130.1,671.85L130.98,672.62L130.56,672.87L130.68,673.16L131.52,673.42L131.16,673.76L131.33,674.17L131.78,674.16L131.73,674.55L132.29,675.24L132.09,675.86L131.74,676.12L131.37,675.93L129.99,677.01L130,678.4L130,678.4L129.7,678.33L129.14,679.23L128.67,678.65L128.02,678.56L127.66,679.42L127.35,679.52L125.84,677.92L123.71,677.54L122.68,676.76L121.95,676.71L121.69,676.25L120.75,676.1L119.74,674.47L119.33,674.35L114.66,675.66L114.34,675.48L113.92,673.56L113.42,673.39L113.27,673.99L112.6,673.63L112.53,674.26L111.46,673.89L111.14,674.36L109.8,674.61L109.8,674.61L109.34,674.12L108.94,674.22L108.97,673.54L110.31,672.46L109.82,672.03L110.09,671.64L109.79,671.02L110.24,671.17L110.48,670.82L110.15,670.28L110.38,669.77L109.86,669.84L109.39,669.31L109.08,669.67L108.48,668.57L109.23,668.32L109.14,667.71L109.84,667.82L109.95,667.26L110.31,667.85L111.14,667.59L111.12,666.94L111.89,666.93L112.01,666.12L110.77,665.45L111.12,665.2L111.03,663.85L111.03,663.85L111.64,663.58L112.02,663.78L111.97,663.26L112.92,662.93L113.44,661.56L113.92,661.4L113.58,662.14L113.92,662.24L114.42,661L114.99,660.62L115.22,661.04L115.92,660.98L116.16,660.44z"
},
{
"id":"RU-OMS",
"title":"Omsk",
"d":"M398.09,596.2L399.38,598.02L397.77,599.04L397.2,599.82L398.62,601.18L397.56,602.25L397.61,602.8L398.96,603.95L400.66,604.76L401.17,607.83L400.86,608.85L401.69,608.91L402.83,611.06L403.01,612.41L403.8,612.18L404.86,614.27L404.86,614.27L405.4,616.73L405.35,617.85L405.84,618.45L405.84,621.38L404.96,622.35L404.28,622.5L402.78,624.29L403.16,625L404.38,624.18L405.02,624.7L404.74,625.27L404.86,626.39L406.1,627.49L406.25,628.17L405.42,628.64L404.15,628.33L402.83,629.12L401.88,629.1L401.35,629.73L400.27,629.92L400.37,630.66L399.02,632.2L399.26,633.73L398.76,633.98L397.86,633.7L397.55,634.09L398.16,635.04L397.86,635.41L398.07,636.13L399.41,636.87L398.74,637.09L397.66,638.6L398.22,638.75L398.31,639.54L398.96,640.48L398.65,641.62L399.17,641.65L399.72,642.56L399.11,644.24L400.47,644.25L400.93,645.61L401.11,644.94L401.74,645.61L401.96,646.68L402.63,647.04L402.8,648.06L401.86,648.71L401.74,649.6L401.95,653.62L401.95,653.62L401.25,653.94L400.75,653.73L399.79,654.22L400.4,655.09L400.33,655.47L397.22,657.76L395.59,657.4L395.3,658.13L394.69,658.17L394.37,659.26L393.15,659.05L392.94,660.12L393.25,660.3L392.67,661.74L391.79,661.41L391.51,660.14L390.99,660.03L390.86,660.65L390.23,660.59L390.31,659.76L389.08,659.48L388.58,660.23L387.44,659.77L387.26,660.55L386.89,660.46L386.77,661L385.82,661.93L385.32,661.54L385.47,660.89L384.37,660.39L384.63,659.54L384.46,659.09L384.96,659L385.1,657.71L385.87,657.48L385.7,657.1L385.94,656.65L387.56,656.89L387.98,654.56L387.14,654.31L387.12,654.71L386.27,655.15L386.38,655.83L385.54,655.34L385.48,655.76L384.68,655.79L383.1,655.27L382.91,654.64L382.44,654.57L382.47,654.02L379.74,653.59L379.34,653.89L379.16,654.65L380.2,654.65L380.61,655.83L379.4,655.35L378.88,656.32L378.14,655.79L378.44,654.75L378.03,654.14L378.54,653.77L378.98,653.87L378.96,653.52L377.64,652.91L377.74,652.3L377.41,652.09L377.32,651.31L376.42,650.77L375.7,650.86L376.34,651.69L376.03,652.42L376.83,652.96L376.66,653.6L376.11,653.33L375.6,652.5L373.76,652.19L373.46,652.88L373.61,653.53L372.96,653.97L371.95,653.89L371.85,653.31L370.8,652.98L369.77,653.87L369.42,653.82L368.76,652.69L369,651.96L368.43,651.64L368.37,651.06L369.72,651.27L369.92,650.4L369.69,648.04L370.43,647.65L370.42,647.16L369.24,646.52L368.68,645.71L368.23,644.29L368.37,641.99L366.97,639.17L365.59,639.67L364.83,639.45L364.83,639.45L364.56,638.24L365.11,637.24L365.62,637.34L366.18,636.95L366.63,635.83L366.6,635.53L365.69,635.33L365.28,633.74L367.13,632.74L367,632.53L365.21,632.73L364.98,632.3L365.26,631.9L366.64,631.97L367.15,631.47L367.69,629.45L367.4,628.1L366.74,627.53L368.38,626.66L367.86,625.54L367.15,625.42L366.98,625.08L367.48,624.64L368.04,624.8L369.24,623.74L368.75,621.84L369.47,622.26L369.85,622.08L370.94,622.3L371.42,621.56L371.83,621.66L372.29,621.33L372.2,620.93L372.62,620.69L372.7,620.13L372.18,618.24L369.31,615.04L368.61,613.04L367.27,612.96L366.95,613.19L366.75,614.56L365.82,614.61L365.45,613.83L364.59,613.5L364.11,612.76L364.14,612.43L366.33,610.46L365.29,608.03L364.64,607.45L364.67,606.72L365.02,603.41L366.76,599.16L367.35,596.89L368.08,597.57L368.98,597.72L369.04,598.55L370.34,599.01L369.98,601.09L370.04,602.77L370.43,603.66L375.41,602.83L375.96,603.11L376.66,604.1L379.91,604.02L381.35,604.53L382.59,603.88L382.32,603.56L383.66,602.16L390.85,602.44L392.96,600.62L393.92,600.36L395.04,599.05L396.33,598.63L396.55,597.65z"
},
{
"id":"RU-PER",
"title":"Perm'",
"d":"M270.86,625.87L269.48,627.31L269.35,627.85L267.56,628.8L266.93,628.8L264.28,625.33L263.61,625.37L262.61,626.22L261.46,626.56L261.03,626.3L259.71,623.83L259.22,623.73L257.65,624.22L256.76,625.07L256.1,625.28L254.87,624.53L253.26,625.06L252.55,624.38L251.81,624.19L251.46,623.28L250.81,623.07L249.25,625.48L249.25,625.48L248.84,623.84L248.2,623.64L247.03,622.17L247.21,621.42L246.8,621.21L246.08,621.6L245.96,622.35L245.52,621.8L245.59,620.84L245.27,620.37L245.39,619.61L246.83,619.43L247.82,617.31L249.48,616.18L249.35,615.86L248.74,615.79L248.56,615.26L248.83,614.74L248.54,613L247.78,613.05L247.58,612.72L247.78,611.82L248.37,611.24L248.19,610.63L246.81,609.38L247.28,608.57L247.26,607.46L247.74,606.27L247.21,604.12L245.98,602.51L245.05,600.59L245.56,599.41L244.75,597.31L244.75,597.31L244.47,595.37L244.69,594.93L244.38,594.4L244.58,593.78L245.61,593.21L244.84,592.2L244.52,590.17L245.11,588.91L244.68,588.54L243.97,588.72L242.84,588.07L241.97,588.06L240.69,585.21L242.03,582.45L242.28,580.44L243.18,580.31L243.18,580.31L243.85,577.43L243.87,575.2L242.38,572.86L242.38,572.86L241.83,573.1L241.67,574.11L235.34,573.07L234.07,572.35L234.07,572.35L234.69,571.29L234.34,570.5L234.48,569.62L232.98,569.1L233.11,568.37L230.36,567.33L231.36,563.11L234.51,563.71L235.41,561.91L237.61,562.08L238.26,560.29L242.31,560.84L241.65,563.11L245.13,563.7L245.51,561.83L253.46,563.06L254.37,560.93L255.16,561.07L255.81,559.29L259.07,559.52L260.03,557.25L262.82,557.94L263.97,554.8L264.89,554.94L265.33,553.81L265.71,553.86L266.03,553.29L268.66,554.16L269.52,553.67L272.42,554.03L281.14,553.91L281.57,553.48L282.74,553.35L283.3,552.25L285.05,551.21L285.05,551.21L285.78,553.03L284.42,556.5L284.43,557.66L284.91,560.98L285.82,562.76L285.81,565.08L285.12,567.91L283.76,571.13L283.84,572.53L282.71,576.39L280.61,578.27L279.56,579.93L278.55,583.39L279.35,584.08L280.35,585.76L281.11,586.22L282.13,586.33L283.34,587.9L283.18,589.18L283.76,590.19L283,591.32L282.99,592.54L283.47,592.7L283.72,593.5L284.22,593.88L285.31,593.69L285.48,593.94L285.18,594.74L285.63,596.54L285.29,597.19L283.92,598.12L283.58,599.19L283.17,599.47L282.2,599.29L280.86,600.4L280.46,601.39L279.33,602.71L279.42,604.02L279.97,604.82L281.12,605.09L281.39,605.56L281.32,606.84L279.94,607.85L278.91,609.09L278.43,607.55L277.18,607.65L276.17,607.24L275.53,607.93L275.52,608.59L274.84,609.48L275.04,610.34L274.31,611.98L274.39,612.51L275.36,613.29L275.03,614.57L275.69,615.5L275.43,615.8L275.71,616.36L275.43,616.55L275.08,616.05L274.71,616.02L272.83,618.17L272.13,618.5L270.47,617.83L269.92,618.29L269.73,619.41L271.04,621.53L270.61,622.64z"
},
{
"id":"RU-PRI",
"title":"Primor'ye",
"d":"M820.13,737.62l3.23,-0.72l0.33,-0.81l-0.31,-2.15l0.98,0.46l0.6,-1.79l0.95,0.01l0.46,-0.33l0.72,0.27l0.73,-0.84l1.05,0.49l0.85,0.03l0.06,0.86l0.66,0.46l-0.5,0.83l0.09,0.38l0.68,-0.03l0.49,-0.58l0.35,0l0.01,0.23l1.19,0.08l-0.21,0.47l1.58,1.17l0.58,-0.77l0.35,-0.03l0.35,0.58l1.33,0.5l0.87,-0.48l1.04,0.16l2.81,-2.16l-0.39,-0.85l0.77,-2.14l1.64,0.34l0.17,0.37l0.86,0.3l2.04,-1.64l0.73,0.26l0.79,-0.38l0.06,-0.7l0.56,-0.08l0.58,-0.56l-0.09,-1.09l-0.62,-0.23l0.51,-0.75l-0.45,0.06l-0.61,-0.43l-0.95,0.21l-1.25,-0.89l-1.21,-0.09l0.18,-0.51l0.79,-0.26l0.17,-0.49l-1.34,-0.79l-0.55,-1.15l1.03,-1.02l1.13,-0.31l0.95,0.31l1.06,-0.46l0.29,-0.61l1.51,-0.26l-0.03,-0.65l0.91,-0.73l1.12,0.34l0.29,1.49l0.54,0.37l-0.06,0.53l1.11,0.14l0.03,0.56l-0.57,0.21l-0.37,0.79l1,0.86l0.46,0.91l-0.12,0.73l-1.61,1.02l-0.12,0.37l0.54,0.59l-0.56,1.33l1.21,0.39l1.22,-0.32l1.02,0.72l0,0l0.34,0.12l-0.44,0.97l-0.94,0.28l-2.03,2.55l-0.66,1.98l-0.98,1.74l-0.03,1.58l-1.17,0.92l-0.56,2.21l-2.37,2.99l-0.6,1.41l-2.33,1.99l-1.6,2.45l-2.43,1.8l-0.26,1.07l-0.94,0.66l-1.38,2.01l0.06,0.57l-0.67,-0.29l-0.1,0.47l-0.28,0.05l0.24,0.27l-0.68,0.46l-0.09,0.91l-0.57,0.89l-1.94,0.84l-0.6,1.46l-1.06,0.91l-0.11,1.39l-0.75,0.28l-0.17,0.63l-0.37,-0.05l0.05,0.71l0.48,-0.17l-0.65,1.29l-1.13,0.78l-0.21,-0.26l0.29,-0.28l-0.65,0.27l0.24,0.15l-0.06,0.62l-0.37,0.25l-0.23,1.02l-1.21,0.36l-1.29,1.17l-0.1,0.41l-0.78,0.06l0.03,0.26l-1.86,1.27l-1.65,0.72l-0.43,0.77l-0.74,0.35l-0.71,0.89l-0.24,-0.24l0.27,-0.01l-0.44,-0.15l-1.07,0.99l-0.49,-0.67l-0.47,0.48l-0.58,-0.08l0.08,0.2l-0.65,0.38h-0.93l-0.69,0.68l-1.13,0.31l-0.29,-0.43l0.65,-0.26l-0.74,-0.63l0.08,-0.3l-0.71,0.09l0.09,0.41l-0.46,0.52l-0.61,-1.05l0.09,-0.66l-0.42,0.03l-0.17,0.55l-0.89,0.11l-0.01,-0.23l-0.41,0l0.05,-0.43l-0.57,-0.3l-0.88,0.9l-0.2,-0.7l0.2,-1.32l-0.24,-0.21l0.33,-0.18l-0.12,-0.76l0.55,-0.26l-0.06,-0.33l-0.54,-0.01l0.34,-0.54l-0.14,-0.27l-0.37,0.01l0.13,0.21l-0.48,0.58l-0.85,0.35l-1.33,1.26l-0.34,-0.23l0.3,-1.14l0.63,-0.32l0.44,-0.77l-0.42,-0.11l-0.15,0.35l-0.83,-0.27l-0.38,0.25l-0.24,-0.68l-0.2,1.27l-0.53,0.3l-0.27,0.94l-0.73,0.97l-0.24,-0.07l-0.06,0.66l-0.97,0.06l0.11,0.68l0.59,-0.05l-1.51,1.03l-0.42,1.34l0.13,0.77l-0.69,-0.59l-0.1,-0.56l-0.53,0.38l-0.48,-0.08l-0.31,0.47l-0.83,-0.4l0.2,-0.65l-0.81,-0.02l-0.51,0.44l1.45,1.2l-0.11,0.61l-0.43,0.03l-0.25,1.1l-0.5,0.66l-0.81,-2.43l0.41,-0.09l0.04,-0.76l-0.6,-0.69l-0.57,0.14l-0.39,-0.42l1.06,-0.86l0.94,-0.33l0.62,0.14l0.36,-0.41l1.41,0.15l-0.05,-0.59l0.69,0.02l0.2,-0.42l-0.27,-0.61l0.75,-1.13l-0.08,-0.7l0.84,-1.88l-0.05,-0.68l-0.84,-0.87l0.32,-0.41l-0.18,-2.22l0.64,-2.54l-1.37,-6.12l-1.06,-1.64l0.93,-0.36l0.12,-0.41l1.27,0.06l0.48,-0.58l1.05,0.14l-0.1,-0.26l1.5,-1.22l-0.29,-0.42l0.23,-0.62l0.7,0.05l0.36,-0.98l0.46,-0.28l0.29,0.57l0.9,0.45l0.9,2.82l-0.52,2.18l1.47,1.26l1.75,0.6l0.98,-1.36l1.11,-3.69l0.87,0.36l1.17,-1.08l-0.36,-1.11l0.51,-2.33l0.79,-0.57l0.37,0.29l1.14,-1.65l0.01,-0.3l-0.37,-0.1l0.53,-0.91l-0.24,-0.08l0.1,-0.71l0.46,-0.35l0.28,0.27l0.17,-0.73l0.44,-0.07l0.49,-1.21l-0.34,-0.88l0.89,-0.8l0.26,0.24l0.43,-0.66l0.08,-0.59l-0.37,-0.19l0.53,-0.54l-0.66,-0.81l0.45,-1.15L820.13,737.62z"
},
{
"id":"RU-PSK",
"title":"Pskov",
"d":"M58.05,590.37L57.89,590.71L57.89,590.71L58.26,591.26L59.26,590.27L60.32,590.42L61.26,590.87L62.21,592.49L62.88,592.42L66.36,593.38L67.17,593.3L69.03,595.14L69.19,596.34L71.1,596.94L71.51,597.95L72.14,598.33L72.97,598.42L73.75,597.99L73.75,597.99L73.75,600.09L71.9,601.45L72.29,602.09L72.08,603.05L73.35,603.44L74.35,604.35L74.43,605.08L75.18,605.08L76.48,605.72L78.38,605.75L78.33,606.6L77.75,607.39L78.39,607.73L77.91,608.98L78.7,609.55L79.39,609.57L77.91,611.24L78.17,611.5L77.71,612.75L80.33,614.56L79.3,617.17L79.59,617.9L80.31,618.38L81.19,617.89L81.53,618.07L81.53,618.07L81.26,618.15L80.78,619.92L80.13,620.56L80.69,620.61L80.23,621.05L80.68,621.68L81.95,622.33L81.74,624.28L83.24,624.64L83.5,625.3L83.17,625.7L83.84,626.18L85.07,626.18L85.46,626.53L84.91,626.62L84.87,627.26L85.37,627.7L84.84,628.21L85.31,629.5L85.14,629.97L84.28,630.53L84.49,631.33L84.26,631.9L84.72,633.44L84.72,633.44L83.1,633.86L82.41,633.54L81.94,633.69L81.35,634.09L81.57,634.35L80.84,635.03L80.84,635.03L80.5,634.86L80.06,635.39L79.72,635.26L79.54,634.61L79.15,634.76L78.79,633.7L78.08,633.45L77.77,632.72L76.81,632.55L76.19,631.93L75.49,631.84L75.13,632.42L74.05,631.67L73.9,631.95L73.25,631.97L72.81,633.15L72.49,632.85L71.68,633.08L70.54,634.03L69.76,633.26L69.98,631.5L70.54,631.25L70.07,630.96L70.15,630.63L68.58,630.39L68.29,629.88L67.57,629.81L66,630.71L65.16,630.69L64.99,629.89L64.66,629.66L64.79,629.1L62.92,628.97L62.73,629.5L62.17,629.45L61.81,629.2L61.96,628.91L61.11,628.34L61.65,626.54L61.09,625.41L61.25,624.56L60.62,623.42L60.92,622.87L60.19,622.61L59.84,621.09L59.24,620.61L59.77,619.67L59.25,619.55L58.85,618.91L57.55,619.41L57.6,618.41L57.99,618.16L58.07,617.46L58.16,616.16L57.94,616.01L58.69,615.15L58.91,613.32L57.39,611.88L56.42,611.41L56.78,610.91L56.68,610.18L55.52,610.27L55.03,609.62L55.66,609.18L55.46,608.43L55.7,608.01L56.29,607.71L56.53,607.89L56.67,607.57L56.3,606.82L56.6,606.75L56.7,606.22L57.84,606.02L58.37,606.26L58.68,605.88L58.47,605.12L57.76,604.91L57.71,603.81L57.36,603.62L57.62,602.91L56.84,602.24L56.2,600.45L56.76,598.77L56.02,593.18L56.37,592.23z"
},
{
"id":"RU-PZ",
"title":"Penza",
"d":"M162.85,657.6L164.06,658.7L163.93,657.83L164.4,657.37L164.8,658.13L165.79,657.54L167.15,657.68L167.94,657.33L168.4,657.62L169,657.52L169.3,656.89L168.85,656.01L169.41,655.09L170.82,655.73L171.68,655.3L172.07,655.4L172.22,655.87L173.02,655.95L174.38,656.7L174.52,657.89L175.14,658.54L176.98,659.09L178.54,658.85L178.94,659.33L180.04,659.03L180.25,658.68L179.39,657.59L179.3,656.82L181.05,655.78L182.57,655.93L183.73,655.68L183.91,656.49L184.26,656.7L185.87,656.17L187.45,656.11L187.91,655.49L187.91,655.49L188.23,655.64L189.32,655.28L190.14,655.83L190.62,656.42L190.82,657.61L192.57,659.77L192.52,661.31L192.89,661.62L194.18,661.43L194.27,661.9L195.59,662.85L195.84,663.53L195.5,664.48L195.92,665.34L195.55,668.15L196.06,669.46L195.93,670L194.93,670.82L194.75,671.48L194.75,671.48L193.94,671.21L193.64,670.42L192.61,670.97L191.83,670.86L191.2,671.8L190.38,671.77L189.88,672.47L189.01,672.87L189.38,673.89L189.14,674.26L186.7,672.93L185.64,674.16L183.33,674.05L182.86,674.25L182.37,675.07L181.04,673.57L179.88,673.52L179.17,673.03L178.87,673.04L178.55,674.25L176.86,675.57L175.88,674.83L174.41,674.62L173.33,673.8L171.5,674.31L170.84,674.85L169.52,673.71L169.04,673.74L168.31,674.36L168.31,674.36L168.34,673.18L169.51,671.84L169.47,671.09L167.35,668.4L164.55,665.91L164.61,665.08L163.48,663.52L162.67,663.48L162.37,663.19L162.53,662.04L161.19,661.19L161.39,658.11L161.13,657.88L161.13,657.88z"
},
{
"id":"RU-ROS",
"title":"Rostov",
"d":"M156.31,699.65l0.56,0.3l0.19,0.92l1.1,0.56l-0.21,1l1.18,0.51l0.58,-0.12l2.07,1.82l0.13,0.87l-0.98,2.83l0.35,1.17l-0.31,0.52l0.06,0.96l2,-0.01l0.58,0.69l-0.2,0.67l1.09,0.03l0.6,0.33l1,1.6l-0.88,1.7l0.15,0.83l-0.29,0.37l-2.72,0.82l-1.43,1.01l0.42,1.46l-0.79,0.37l0.36,0.79l-0.48,0.67l0.03,0.72l3.23,0.48l1.89,1.46l0.22,1.08l1.77,2.95l0.53,-0.1l0.24,-0.47l0.83,0.08l-0.08,0.88l0.66,0.48l2.99,-0.72l0,0l0.67,1.69l0.59,0.29l0.36,0.01l0.28,-1.15l1.24,-0.5l0.25,-1.08l0.59,0.11l-0.19,0.41l0.81,0.49l-0.09,2.86l-0.49,1.5l-0.06,1.4l-0.81,0.75l-0.44,-0.03l-1.9,2.59l0.83,0.3l-0.31,0.83l0.53,1.27l-0.16,0.27l-0.77,0.4l-0.03,-0.75l-0.51,-0.42l-1.01,2.47l-1.58,0.03l-3.12,-2.5l-1.93,0.53l-1.16,-0.53l-0.78,-0.8l-2.53,-1.07l-0.17,0.17l0.33,0.83l0.84,1.23l-0.35,0.33l-0.87,-0.22l-0.69,0.37l0.09,0.95l-0.73,0.54l-0.71,-0.44l-0.6,0.22l-0.26,0.37l0.55,1.08l-0.13,0.41l0,0l-1.83,-0.08l-0.47,0.68l-1.57,-0.33l0,0l-0.68,-1.31l-0.78,-0.52l-0.2,-1.34l-1.34,0.51l-0.75,-0.57l-2.7,0l-0.66,-0.81l0.25,-0.54l-0.43,-0.98l-1.5,-0.67l0.49,-1.73l-0.71,-0.54l-3.36,-0.35l-0.54,-0.41l-1.39,0.79l-0.08,0.67l-0.72,0.68l-1.5,-0.12l-0.5,0.59v-0.69l0.64,-1.46l-1.52,0.03l-0.11,-0.42l0,0l1.26,-0.35l0.43,-0.62l1.5,-0.8l1.35,0.23l0.11,-0.41l-0.37,-0.25l-0.31,-1.13l0.21,-0.76l-0.4,-0.25l-1.66,0.17l-0.02,0.73l-2.76,0.61l-0.03,0.29l-0.43,-0.35l0.39,-0.96l1.04,-0.33l0.56,0.13l-0.03,-0.45l-1.54,0.2l-1.2,0.87l-1.1,0.26l0.03,-0.56l0.63,-0.26l-0.06,-0.5l-0.73,-0.13l0.56,-0.73l-0.06,-1.6l0.56,-0.82l1.74,-0.29l0.38,-0.6l0.7,0.12l0.2,-1.29l0.62,-0.75l1.71,0.4l1.8,-0.41l0.33,0.36l0.33,-0.19l0.48,0.35l1.67,0.04l0.61,-1.79l-0.36,-0.47l0.65,-0.1l0.42,-1.95l0.35,0.05l0.15,-0.3l-0.23,-0.69l-0.42,0.18l-0.55,-0.26l0.69,-0.51l-0.68,-1.1l-0.01,-1.06l-1.16,-0.22l-0.22,-0.36l1,-2.45l1.39,0.53l0.76,-0.9l-0.27,-0.33l-0.44,0.4l-0.59,-0.38l-0.54,0.01l-0.09,0.25l-0.58,-1.13l-0.6,-0.11l0.04,-0.5l1.9,-0.17l0.63,-1.22l1.26,-0.75l-0.28,-2.12l0.41,-0.78l-0.07,-0.61l0,0l0.54,-0.68l2.2,0.48l0.89,-0.55l1.92,-0.54l1.06,-2.46l1.96,-1.81L156.31,699.65z"
},
{
"id":"RU-RYA",
"title":"Ryazan'",
"d":"M147.74,638.98l0.92,-0.16l0.15,0.3l-0.49,0.16l0.21,0.4l0.58,-0.02l0.47,-0.63l0.42,0.13l-0.12,0.74l0.42,0.79l1.08,-0.04l0.21,-0.37l0.66,0.3l0.18,-0.76l0.68,0.08l0.61,1.49l0.33,0.06l-0.01,-0.61l0.57,-0.56l0.44,0.06l1.33,1.21l1.22,-0.44l0.4,0.52l0.25,-0.27l0.65,0.1l0,0l-0.1,0.48l0.57,0.65l1.09,-0.64l-0.16,1.29l1.62,0.39l0.98,-0.65l0.29,0.24l0.37,-0.31l0.46,0.37l-0.45,0.37l0.04,1.35l0,0l0.06,0.29l-0.46,-0.07l-0.4,0.41l0.4,0.76l0.75,0.69l0.22,-0.26l0.15,0.43l0.63,-0.15l0.09,1.02l0.53,0.35l-0.6,0.39l0,0.73l-0.45,-0.26l-0.26,0.86l0.48,0.17l0.31,0.61l-0.98,0.18l-0.12,0.61l-1.5,0.94l-0.71,-0.29l0.71,1.09l0.79,-0.36l-0.18,-0.32l0.71,-0.34l0.39,0.59l1.13,-0.07l0.29,0.68l-0.95,-0.04l-0.48,0.28l0.29,0.45l-0.15,0.25l-0.66,-0.45l-0.55,0.4l-0.39,-0.72l-0.36,0.58l1.73,1.6l-0.89,0.81l-0.34,0.77l0,0l-1.71,0.27l0,0l-1.32,-0.07l-0.84,0.32l-0.17,-0.29l-1.19,0.35l-0.15,-0.44l-0.25,0.62l-0.99,0.03l-0.35,2.63l-0.48,0.11l0.17,0.49l-0.38,0.21l-0.36,-0.19l-0.21,0.88l-0.46,-0.06l-0.31,-0.7l-1.06,-0.46l-0.43,0.49l-0.24,-0.1l-0.4,-0.88l-0.57,-0.03l-0.19,0.65l-0.55,0.11l0.04,0.62l-0.56,-0.71l-0.48,0.32l0.24,0.8l-0.95,0.54l-0.39,-0.43l-0.25,0.92l-0.72,-0.13l0,0l-0.58,-0.69l-0.81,-0.17l-0.58,-0.65l0.29,-0.07l0,-0.87l-0.83,-0.5l-0.39,0.28l-0.17,-0.4l-1.29,0.79l-0.2,1.11l-1.13,0.24l-0.51,-0.23l-0.92,0.38l-0.88,-1.9l-0.34,-0.28l-0.5,0.22l-0.35,-0.2l0,0l0.21,-1.73l0.46,-0.55l-0.84,0.03l-0.19,-0.39l0.24,-0.43l-0.6,-0.07l0.35,-0.26l-0.13,-0.64l0.64,-0.46l-0.69,0.13l-0.28,-0.23l0.05,-0.54l-0.4,-0.18l0.21,-0.26l-0.58,-0.24l0.01,-0.66l0.58,0.01l0.25,-0.6l-0.75,-0.3l-0.18,-0.73l0,0l0.35,-0.18l0.06,-1.01l0.51,0.15l0.22,-0.56l0.6,0.43l0.14,-0.49l0.37,-0.11l-0.05,-0.45l-1.26,-0.52l0.4,-0.72l-0.37,-0.14l0.2,-0.81l0.72,-0.26l0.41,0.32l0.22,-0.35l0.72,0.02l0.3,-0.33l0.52,0.2l0.02,-0.82l0.96,-0.51l-0.35,-0.09l0.58,-0.82l-0.08,-0.47l0.54,-0.51l-0.08,-0.39l0.59,-0.63l0.46,-0.02l0.14,-0.58l0.47,0.27l0.63,-0.24l0.25,0.19l0.39,-1.31l-0.34,-0.3l-0.61,0.22l0.49,-0.89l1.41,-0.18l1.15,-0.74l0.23,-0.78L147.74,638.98z"
},
{
"id":"RU-SAM",
"title":"Samara",
"d":"M218.25,648.68L219.31,649.06L219.92,649.95L220.49,649.39L220.83,649.57L221.35,650.42L221.19,650.98L221.56,651.13L223.14,649.69L224.53,650.95L224.96,649.81L224.89,648.64L226.08,647.55L226.05,647.04L226.98,647.43L227.66,646.84L227.54,647.95L227.85,648.1L228.66,647.11L229.13,647.88L230.89,648.91L231.73,649.08L231.69,649.86L232.43,650.4L232.56,651.04L234.26,649.68L234.89,650.02L235.41,649.59L235.71,649.68L236.03,650.49L236.03,650.49L234.9,651.15L234.69,652.85L234.34,652.98L234.41,653.54L235.25,654.42L235.22,655.07L234.79,656.69L233.82,658.2L233.54,659.92L232.73,661.12L233.19,662.21L234.19,662.54L233.15,662.98L233.26,663.51L232.64,665L233.11,665.62L232.76,666.82L231.66,667.44L230.16,668.86L230.28,669.67L229.76,671.03L229.26,670.84L228.75,671.36L228.3,672.67L228.94,673.35L228.94,673.8L227.62,675.32L228.08,677.48L227.75,678.06L226.16,679.67L223.87,681.37L223.87,681.37L222.38,679.17L220.37,678.49L219.86,678.67L219.06,677.79L219.25,677.49L218.28,677.29L217.8,676.82L216.7,676.79L215.42,675.89L215.32,674.71L214.89,674.24L214.53,674.28L214.39,674.88L213.88,674.77L213.25,674.14L213.39,673.6L212.65,673.18L210.24,673.39L208.86,672.29L208.29,671.42L207.8,671.47L207.39,670.97L206.71,670.8L205.69,671.59L205.49,671.07L206.21,669.91L206.1,669.54L206.1,669.54L206.65,669.31L207.32,667.95L206.71,667.24L205.71,667.12L205.84,666.69L205.48,666.5L204.8,666.85L204.62,666.54L204.89,665.51L204.45,664.98L204.56,664.03L204.01,663.77L203.24,662.59L203.71,662.07L203.72,661.58L204.72,661.11L206.06,661.57L206.32,660.83L206.16,660.03L205.68,659.64L205.75,659.27L206.19,658.97L207.54,659.32L207.82,659.11L207.71,658.79L206.64,658.3L207.02,657.88L209.39,658.76L210.71,656.95L212.11,657.12L211.75,656.57L212.4,656.8L213.65,656.54L214.71,657.29L216.24,656.43L217.45,656.92L217.78,656.56L217.17,655.81L218.93,654.33L219.03,652.99L219.58,652.14L219.19,651.3L219.27,650.33z"
},
{
"id":"RU-SA",
"title":"Sakha",
"d":"M830.76,305.93l-0.27,-0.86l1.25,0.43l3.25,3.87l0.52,1.32l1.06,1.07l0.18,1.67l-0.85,1l-0.79,-0.78l0.03,-0.72l-0.86,-1.31l-1.47,-1.23l-0.36,-1.62l-0.76,-0.81l-0.13,-1.04l-0.33,0.2l0.25,0.69l-0.76,-0.3L830.76,305.93zM844.62,372.12l-0.01,0.26l-0.48,-0.63l-0.29,0.09l-0.12,0.68l-0.94,-0.37l-1.23,-1.05l0.16,-0.74l0.53,-0.14l0.78,0.99l-0.35,-0.53l1.61,-0.81l1.58,0.1l0.12,0.39l0.26,-0.3l0.36,0.29l0.39,-0.27l1.22,0.03l0.71,1.06l-0.04,0.71l-1.13,1.83l-0.75,0.29l-0.87,-0.74l-0.17,-0.74l-1.17,-0.15L844.62,372.12zM863.39,325.75l2.31,-0.14l2.16,-2.35l1.04,-2.39l0.39,-1.83l0.39,-0.3l-0.34,0.04l0.15,-0.81l0.48,-0.49l0.6,-1.73l0.81,-0.94l0.87,0.57l0.71,-0.06l1.39,-0.93l3.66,-0.92l1.48,1.42l2.08,0.77l4.91,5.26l1.37,2.04l0.97,2.31l-0.07,0.6l-0.53,0.58l-0.12,1.5l0.49,2.73l0.34,0.43l-2.57,1.05l-3.46,-1.3L880.9,331l-1.28,-0.73l-4.88,-0.98l-1.83,-0.8l-3.49,-2.33l-1.18,-0.26l-2.12,0.35l-3.18,1.85l-0.66,-0.13l-0.67,-1.45l0.4,-0.75L863.39,325.75zM871.01,307.3l-0.37,0.88l0.31,1.31l-0.24,1.35l-0.54,0.83l-0.89,0.24l-0.93,0.58l-0.69,0.92l-0.39,-0.03l0.12,0.36l0.69,-0.13l-0.13,0.2l-1.16,-0.09l-0.82,-0.71l-1.19,-2.44l-0.33,-1.48l0.2,-3.1l0.41,-0.82l0.93,-0.6l3.39,-0.39l1.3,0.76l0.41,1.07L871.01,307.3zM830.84,272.12l0.35,-0.28l0.53,-2.1l0.18,-2.32l-0.24,-2.43l0.72,-3.06l0.04,-0.84l-0.39,-0.45l0.36,-1.03l1.6,5.32l1.03,1.28l1.03,0.67l-0.92,1.35l-0.82,2.18l-0.12,0.62l0.65,1.07l-1.34,1.91l-2.17,0.25l-0.27,-0.24L830.84,272.12zM996.22,475.53l-0.84,1.66l1.13,2.21l-0.42,0.47l-0.88,-0.21l-0.57,0.22l-0.51,-0.96l-0.99,-0.26l-1.63,0.74l-1.4,0.19l-0.83,1.36l-0.86,0.56l-0.02,0.99l-0.32,0.43l-2.19,-0.12l-1.33,-1.06l0.56,-0.49l-0.08,-0.74l-1.8,-1.17l-0.24,-1.42l-0.32,-0.13l-1,1.15l-0.16,1l-0.74,0.49l-0.72,-0.37l-1.67,0.08l-0.95,-0.77l-0.37,-1.21l-1.23,0.8l-1.54,-0.48l-1.6,0.25l-0.44,-0.85l-0.81,0.17l-0.49,0.92l-0.96,0.26l-0.32,-0.92l-0.75,-0.05l-0.45,-0.52l-0.65,-0.19l-1.11,0.69l-0.03,0.83l-1.25,0.79l0.2,0.79l0.93,0.84l-0.07,1.3l-1.3,1.97l-0.92,0.04l0.15,-0.98l-0.39,-0.47l-0.94,0.24l-1.31,-0.13l-0.52,0.57l-1.08,0.34l-0.21,1.52l0.51,0.19l-0.3,1.4l0.26,0.6l-1.09,1.36l-0.2,0.95l0.82,0.74l-0.14,0.83l-0.6,0.83l-0.83,0l-0.45,0.47l-0.01,0.64l-0.59,0.21l-1.19,-0.39l-0.92,0.75l-1.05,0.28l0.01,0.56l-0.6,0.78l-0.08,1.85l-0.92,0.51l0.93,3.71l1.11,0.58l0.13,0.48l-0.33,0.78l-1.43,0.83l-0.7,1.33l-0.97,0.18l-0.21,0.43l0.81,1.26l-0.33,0.81l-1.76,0.44l-0.49,-0.29l0.42,-1.04l-1.36,-0.6l-1.58,0.72l-0.69,0.01l-0.78,1.73l-0.54,0.19l-0.79,-1.03l-0.75,0.6l-0.33,-0.42l-0.74,0.61l-1.17,0.14l-1.56,-0.38l-0.41,0.67l0.09,2.27l-0.78,-0.03l-1.09,-0.68l-1.04,0.14l-0.26,-0.83l-1.11,-0.93l0.12,-0.92l-0.29,-0.62l0.71,-0.62l0.05,-0.61l-1.15,-0.64l0.01,-0.65l-1.01,-0.16l-0.35,0.73l-2.49,1.85l-0.83,-0.37l0.16,0.73l-0.97,-0.1l-0.79,-0.85l-1.02,-0.3l-0.32,0.76l-0.84,-0.72l-0.82,0.57l-1.06,-0.55l-0.13,-0.92l-0.82,-0.42l-1.47,1.66l-0.82,0.42l0.26,1.32l1.54,1.97l-1.65,2.55l-0.3,0.84l0.09,0.99l-0.71,0.24l-1.25,-0.22l0.26,-0.59l-1.21,-0.95l0.5,-1.39l-0.43,-0.44l-1.26,0.82l-0.74,-0.21l-0.21,0.99l-0.8,-0.05l-2.4,-1.85l-2.2,0.34l-1.2,-0.58l-0.42,0.33l-0.71,2.54l-0.87,1.2l-3.47,1.45l-0.2,0.69l0.33,1.95l-0.5,1.69l-1.08,1.46l0.15,0.83l-0.61,1.37l0.09,0.71l-0.93,1.21l-0.29,0.92l0.65,0.89l0.01,0.71l-0.49,0.58l1.4,1.13l0.13,1.92l-0.62,0.97l0.08,0.64l0.62,0.42l-0.46,1.66l0.51,0.62l-0.26,0.4l-0.8,0.24l-0.27,-0.28l-0.8,0.77l0.44,0.73l-0.57,1.15l0.18,1.2l-0.3,0.84l-0.67,0.1l-0.61,1.11l-0.39,-0.18l-0.51,0.71l-0.53,0.17l0.09,0.93l0,0l-0.86,0.86l-0.53,2.21l-1.14,0.4l-0.77,1.04l-1.08,0.04l-0.47,0.34l-0.78,-0.42l-0.13,-0.63l0.44,-0.72l-0.24,-0.71l0.31,-0.94l-0.41,-0.18l-1.1,0.58l-0.58,1.17l-0.86,-1.55l0.26,-0.37l-0.33,-0.77l-0.66,-0.14l-0.86,0.52l0.04,-0.38l-0.68,-0.48l-0.04,-0.8l-0.92,0.39l0.05,1.23l-0.79,0.95l-0.08,0.83l-0.63,0.22l-0.26,-0.75l-1.79,-0.52l-0.92,1.05l-0.77,0.1l-1.11,-0.78l-0.45,-1.88l-0.72,0.02l-0.42,0.59l-1.01,0.35l-0.52,-1.04l-0.87,-0.23l-0.14,-0.5l-0.66,-0.34l-0.47,-0.7l0.03,-1.03l-0.85,-0.53l-0.74,-1.12l-0.17,-0.86l-0.67,0.33l-0.82,-0.06l0.04,-1.01l-0.9,0.05l-0.43,-0.78l-1.01,0.01l-0.71,1.35l-1.45,0.05l-0.66,0.51l-0.69,4.5l0.43,0.65l-0.69,0.76l-0.09,0.54l-1.35,-0.08l-0.66,0.33l0.36,1.14l-1.23,3.64l-0.64,0.3l-1.02,1.79l-1.38,0.3l-0.96,0.7l-0.93,-0.31l-0.46,0.48l0.02,0.85l-0.38,0.45l-1.37,0.01l-0.48,0.37l-0.36,-0.55l-0.43,0.76l0.33,0.87l-0.31,0.56l-1.71,1.5l-0.66,-0.16l-0.22,0.32l0.26,0.74l-1.05,2.4l2.19,2.59l-1.41,3.35l0.45,1.09l-1.07,1.98l-0.01,1.32l-0.27,0.45l0.32,0.85l-0.16,1.37l0.57,0.72l-0.75,1.17l0.18,1.2l0.52,0.28l0.03,0.32l-0.57,0.69l-0.82,0.03l0.15,-0.8l-0.29,-0.66l-0.48,0.41l-2.61,-0.04l-1.17,1.18l0.14,0.92l-0.3,0.47l-1.99,1.83l-1.54,0.26l-1.3,1.22l-0.5,0.04l-1.12,-0.69l-1.58,-0.11l-1.79,-0.56l-0.09,-0.39l-1.44,-0.82l-1,-0.17l-0.8,0.23l-2.25,3.08l0.01,0.9l-0.71,0.76l0,0.36l-0.65,0.35l-1.75,-0.67l-0.43,0.16l-0.88,-1.05l-0.41,-0.03l-0.85,0.71l-0.77,-0.01l-0.76,-0.68l-0.65,0.21l-1.74,-0.91l-2.47,0.54l-0.86,-0.49l-1.93,0.8l-0.95,-0.17l-0.64,0.32l-0.24,1.04l-0.61,0.27l-0.55,-0.15l-0.44,1.15l0.68,0.7l-0.32,0.77l-1.61,0.33l-0.74,2.39l0.38,0.97l-0.68,0.83l-0.25,0.96l-1.81,-0.23l0.46,3.33l-0.53,0.19l-0.37,0.77l0.45,1.86l-1.04,0.06l-0.56,-0.67l-1.2,-0.5l-0.53,-0.83l-1.33,0.32l0.16,1.15l0.7,0.17l-0.18,0.84l0.55,0.67l1.13,0.46l-0.37,0.67l2.23,2.36l-0.26,0.5l-0.41,0.08l-0.14,0.61l-0.57,0.05l-0.8,0.72l-0.1,0.54l-1.12,1.38l-0.03,1.06l-0.45,0.87l-0.39,0.25l-1.08,-0.54l0.01,-0.39l-0.39,0.06l-0.21,0.94l-0.53,0.12l0.26,0.95l0.71,0.08l1.08,1.02l2.6,4l-0.14,0.55l-0.99,0.69l-0.09,1.48l0.55,0.96l-0.27,0.48l-0.58,0.16l-0.68,-0.97l-0.57,0.89l-0.46,0.1l-0.59,-0.65l-0.57,0.2l-0.59,0.89l-0.18,2.26l-1.3,2.3l-0.59,1.96l0.06,0.77l0.6,0.92l0.01,1.12l0,0l-1.88,-0.92l-3,0.24l-0.58,0.54l-0.85,-0.28l-0.7,0.3l-0.48,-0.63l-0.47,-0.08l-0.41,0.31l-1.34,-0.36l-0.46,0.26l-0.75,-0.16l-0.51,0.39l-0.66,-0.15l-0.42,0.42l-0.61,-0.08l-0.86,0.45l0.77,1.25l-1.12,1.01l-0.7,-0.28l-0.69,0.21l-0.86,-0.63l-0.97,-0.03l-0.49,-0.65l-1.63,-1.01l-0.71,-0.18l-0.44,0.36l-0.81,-0.18l-0.75,0.34l-0.69,-0.72l-0.59,0.09l-0.63,1.14l-1.3,0.3l-0.63,-1.28l-1.82,-0.05l-0.84,0.29l-0.5,0.88l-1.42,-0.33l-0.24,-0.39l-1.35,0.92l-1.35,-0.31l-0.82,0.15l-0.63,-0.16l-0.13,-1.33l-0.5,-0.33l-1.55,-0.52l-1.17,0.34l-1.54,-1.4l-1.88,-0.13l-1.03,0.5l-1.84,-0.62l-0.04,-0.38l-1.3,0.07l-0.52,-0.37l-0.33,-1.49l-1.1,-0.72l-1.99,-3.28l-0.93,-0.59l-2.94,0.11l-1.19,-0.34l-1.35,-0.63l-1.4,-1.5l-0.41,0.98l-0.57,0.35l-0.67,-0.04l-3.58,-3.36l-1.35,-0.09l-0.79,0.31l-1.68,-0.33l-0.04,-1.13l-0.44,-0.25l-0.26,-1.15l-0.39,-0.39l-3.92,-0.76l-1.47,0.16l-0.43,-0.21l-2.08,0.38l-2.06,1.39l-2.26,0.2l0,0l-1.04,-0.98l-0.25,-1.84l0.43,-0.57l-1.94,-3.37l0.39,-2.15l-0.96,-0.49l-0.48,0.2l-0.04,0.84l-0.4,0.33l-0.4,-0.73l0.13,-1.08l-0.23,-0.65l-0.76,-0.4l0.51,-3.45l0.39,-0.87l-0.32,-2.38l0,0l0.24,-0.7l-0.63,-1.6l0.39,-0.58l-0.09,-0.71l-2.23,-1.47l0.37,-2.86l-0.5,-1.55l0.45,-0.96l-0.48,-0.31l-0.38,-2.68l0.98,-1.36l-0.63,-1.66l-2.67,-0.93l-0.28,-1l-0.68,-0.8l-1.01,0.26l-0.15,-0.49l-0.35,0.99l-0.48,0.26l-0.23,1.32l-0.77,0.37l-0.38,-0.33l-0.37,-1.34l-1.05,0.83l-0.71,-0.3l-1.39,0.16l-0.88,-0.66l-0.26,-0.68l0.23,-0.73l-0.1,-2.67l-0.65,-0.62l0.47,-0.63l0.66,-0.26l0.56,-1.62l-1.55,0.37l-0.36,-0.38l-0.04,-1.09l-0.35,-0.58l-0.56,-0.62l-1.05,-0.35l-0.09,-0.76l-0.86,-0.18l-0.74,-0.97l-1.41,0.13l-0.29,-0.53l-0.81,-0.01l-0.04,-0.48l-0.76,-0.39l-1.2,-0.01l0.05,-0.55l-0.88,-0.63l-0.55,0.01l-1.94,1.15l-0.77,0l-0.51,-0.44l-1.02,1.48l-0.26,1.53l-0.55,0.97l-0.56,0.32l-1.41,-0.05l-1.26,1.8l0.34,0.79l-0.15,0.72l-0.78,0.15l-1.44,1.17l-0.6,0.83l0.01,0.84l-0.51,0.2l-0.51,-0.25l-0.38,0.32l0.07,0.6l-0.68,0.06l-0.35,0.52l-0.02,0.57l-0.78,0.08l-0.81,0.8l-0.28,1.13l-1.01,0.79l0.38,1.43l-0.15,0.73l-1.44,1.32l-0.8,-0.09l-2.08,0.78l-0.94,1.55l-0.77,-0.55l-0.01,-0.77l-0.5,0.39v2.62l-0.49,0.34l-0.51,-0.02l-0.27,-1.42l0.31,-1.2l-0.19,-1.37l0.73,-0.81l0.9,-0.43l0.01,-1.19l-1.46,0.01l-0.97,0.43l0.32,-1.89l-0.6,-1l-1.92,2.68l-2.01,0.5l-0.71,0.75l-1.09,-0.78l-1.36,0.34l-0.34,0.6l-0.6,-0.06l-0.43,-0.57l-0.89,0.27l-1.89,-0.31l-0.46,0.59l-0.5,1.69l-0.6,0.65l-0.71,0.06l-0.87,0.53l-2.7,-0.13l-0.9,0.33l-0.32,-1.28l-0.78,0.35l-0.32,-0.31l0.09,-1.06l-0.87,-1.05l-0.21,-0.87l-1.37,-0.65l0.13,-0.73l0.48,-0.51l-0.42,-0.32l0.19,-0.71l1.24,-1.47l0.27,-0.96l-0.32,-0.87l1.4,-2.11l0.01,-0.97l0.85,-1.3l-0.52,-1.1l0.44,-1.89l0.59,-0.76l0.26,-1.15l0.68,-0.46l-0.1,-1.04l0.77,-0.66l0.1,-0.63l0.67,-0.3l0.04,-0.43l-0.56,-0.42l0.09,-0.41l1.34,-0.23l0.43,-1.01l-0.37,-0.69l1.68,-2.33l0.31,-2.16l-0.79,-0.58l-1.22,0.18l-0.85,-0.61l-0.47,-1.17l-0.47,-0.35l-0.65,0.29l-0.47,-0.16l-0.33,-0.67l0.3,-3.32l-1.64,-2.58l-0.37,-1.67l0.54,-1.62l0.63,-0.79l1.39,-0.7l-0.09,-0.84l0.6,-1.2l-0.41,-1.3l0.31,-0.51l-0.71,-1.89l-2.13,0.04l-0.84,0.57l-1.08,-1.57l0,-1.3l0.54,-0.48l0.03,-0.6l0.53,-0.38l0.26,-1.19l1.23,-1.16l0.07,-0.49l-1.05,-1.2l-0.31,-0.8l-0.51,-6.37l-0.91,0.28l-1.47,-2.94l-1.47,0.21l-1.86,-0.94l-1.14,0.04l-1.71,0.57l-0.29,-0.69l1.16,-2.12l0,-1.08l2.9,-0.2l0.63,-0.63l-0.03,-0.58l-0.4,-0.28l0.33,-1.45l-0.48,-0.69l-1.19,-0.2l-0.3,-0.64l-0.33,-1.44l0.38,-0.96l-0.52,-0.43l-0.06,-1.13l-0.38,-0.11l-0.84,0.85l-1.01,-0.43l-0.79,0.45l0,0l-0.09,0.61l-0.89,0l-2.24,-1.51l-0.74,-0.11l-0.53,0.45l-1,0l-0.23,-1.49l-1.89,-0.17l-0.41,-0.89l-1.27,0.1l-0.68,-1.95l-0.61,0.35l0.12,0.65l-0.33,0.36l-1.88,0.23l-1.03,0.47l-0.45,-0.57l0.31,-0.55l-0.11,-0.77l-0.96,-0.27l-0.92,0.95l-0.99,-1.51l0.31,-0.4l-0.31,-1.34l1.02,0.04l0.25,-0.41l-0.28,-0.81l0.76,-1.36l-0.25,-0.67l0.24,-0.81l0.38,-0.08l0.44,0.69l0.78,-0.27l-0.71,-0.59l-0.01,-0.74l-0.55,-0.47l-0.07,-0.84l0.29,-0.5l0.87,-0.08l0.25,-0.76l0.8,-0.27l0.75,-1.23l0.79,0l-0.58,-1l0.61,-1.4l0.77,-0.56l0.82,-0.12l0.6,0.27l0.25,-1.53l1.23,-0.91l-0.27,-0.38l-1.1,0.02l-1.14,-1.72l-1.42,-0.82l0.05,-6.4l-0.38,-1.04l-1.89,-1.2l0.1,-4.37l0.92,-1.68l-0.41,-2.29l0.29,-1.32l-0.58,-0.72l-0.14,-0.92l-0.74,0.2l-0.31,-0.33l0.55,-0.92l0.02,-0.95l-1.4,0.25l-0.15,-0.92l-0.81,-0.17l-0.77,0.42l-1.33,-1.32l0.17,-0.58l2.72,0.02l0.61,-0.37l0.49,-2.41l1.52,-0.22l1.29,-1.28l1.3,0.45l0.7,-0.72l0.33,-1.57l0.11,-4.91l0.86,-10.31l0.19,-9.14l-0.4,-4.52l-2.6,-5.48l-2.76,-4.87l0.26,-1.35l0.68,-0.39l0.57,-1.2l1.03,-0.83l1.26,0.8l2.57,-0.25l3.29,-2.28l2,-0.69l1.31,0.12l0.42,-0.31l0.62,-1.57l1.6,-1.35l3.69,-0.24l0.59,0.15l-0.06,1.04l0.35,0.52l1.41,0.24l1.31,-0.46l0.85,-2.23l0.19,-1.96l0.54,-0.6l0.05,-0.55l-0.97,-0.52l0.2,-1.69l-0.51,-0.59l0.12,-1.21l1.37,-0.55l0.38,-1.2l-0.28,-1l0.32,-0.54l4.83,-0.78l-0.34,-0.92l-1.3,-1l0.05,-1.28l0.51,-0.4l-0.27,-0.79l0.38,-0.76l0.88,-0.73l1.13,-0.21l0.87,-1.07l2.65,-0.85l2.11,-1.58l1.47,-0.18l0.71,-1.32l3.01,-0.87l1.25,-1.76l0.46,0.02l0.57,0.94l0.4,-0.21l0.37,-1.08l1.04,-0.12l0.35,-0.94l-0.27,-0.71l0.21,-1.2l1.03,-0.24l0.01,-1.1l-0.63,-0.45l-1.12,-0.15l-1.26,-1.71l-1.5,-0.73l-0.24,-0.75l0.2,-2.19l-0.67,-6.01l0.22,-3.11l-0.31,-4.5l-1.37,-0.48l-0.47,-0.94l-0.79,-0.23l0.3,-2.31l-0.78,-1l-1.08,0.04l-0.58,-0.85l-1.45,0.07l-0.6,-1.03l0.36,-0.94l0.72,-0.77l0.02,-1.41l-0.74,-0.89l-1.42,-0.34l0.18,-1.21l-0.5,-0.35l-0.65,0.1l-0.44,-3.79l0.31,-1.98l0.85,-2.34l-1.21,-0.24l0.52,-0.98l0.94,-0.2l0.08,-1.03l-0.62,-1.07l0.46,-0.9l-0.29,-0.61l-1.31,-0.37l-1.54,0.6l-0.75,-1.19l1.48,-1.6l-0.15,-1.38l-2.97,-1.49l0.44,-0.78l3.49,-0.05l1.54,-4.51l0.72,-0.05l0.81,0.54l0.4,-0.32l-0.66,-1.86l-1.25,-0.28l0.26,-2.22l0.57,-0.85l1.88,-1.42l0,0l1.82,2.32l2.46,1.41l3.3,0.68l3.3,-0.39l0.78,-0.55l0.63,-1.53l-1.35,-4.38l0.2,-0.67l1,1.99l1.41,1.38l0.56,2.09l1.19,2.64l0.31,2.18l-1.08,1.21l-0.74,2.5l0.65,0.81l0.27,0.94l1.48,0.89l0.13,1.75l-0.39,0.8l0.59,0.13l0.33,-0.29l1.03,-2l1.18,0.25l0.71,-0.39l0.42,-0.67l-0.52,-0.21l-0.89,0.61l-0.33,-0.2l-1.93,-2.12l-0.36,-0.69l0.08,-0.88l-0.32,-0.36l3.21,-1.05l1.15,-0.98l0.99,-0.29l1.97,0.47l2.63,-0.48l1.35,-1.16l0.5,0.07l-0.46,-0.42l1.17,-0.77l0.64,-0.3l0.81,0.5l-0.3,-0.41l0.23,-0.19l0.9,-0.09l0.6,0.41l0.07,-0.2l2.39,0.27l2.07,0.94l1.68,-0.4l0.85,0.2l5.3,2.23l3.38,0.23l1.25,-0.42l5.04,0.69l0.63,0.46l-0.01,0.99l0.48,0.07l0.69,0.96l-0.72,0.6l-0.69,0.1l-0.69,-1.01l-0.13,0.24l-0.67,-0.28l-0.11,0.5l-0.98,0.98l-0.01,1.06l0.49,0.22l0.02,0.31l-0.77,1.37l0.29,0.5l-0.04,1.13l0.85,1.2l3.08,1.3l1.4,0.99l2.28,0.72l1.61,1.37l1.35,-0.5l0.57,0.1l1.41,0.58l3.54,0.33l3.08,1.24l2.55,-0.89l1.6,-0.16l1.63,0.83l0.05,-0.44h0.76l0.16,0.44l1.83,-1.04l0.61,0.97l0.34,-0.36l1.02,0.85l1,0.09l-0.27,-1.11l0.39,0.36l0.69,-0.03l-1.71,-1.54l0.08,-0.32l0.48,-0.07l1.35,1.6l2.13,0.76l0.22,0.79h0.55l0.55,-0.42l0.41,-1.2l0.49,-0.1l-0.28,-1.86l0.74,-1.71l-0.1,1.06l0.36,-0.08l0.12,-0.88l0.66,0.56l0.15,-0.34l0.46,-0.03l-0.67,-0.33l-0.58,-0.93l-0.68,-0.01l1.24,-1l0.51,0.39l0.26,-0.64l-0.79,-0.04l-0.12,-0.39l-0.25,0.57l-0.13,-0.88l-0.48,-0.14l0.39,-0.21l0.13,-0.71l-0.37,0.41l-0.06,-0.41l-0.67,-0.17l0.63,-0.42l-0.73,-0.43l-0.2,-0.78l0.15,-0.3l0.97,-0.23l0,-0.31l-0.59,0.23l-0.28,-0.16l0.13,-0.32l-0.39,0.24l-0.72,-0.41l0.29,-0.25l0.14,0.37l0.32,-0.07l-0.38,-0.9l0.32,-0.54l0.25,0.35l-0.16,0.43l0.77,0.84l0.23,-0.09l-0.45,-0.68l0.16,-1.1l-0.24,0.34l-0.49,-0.68l-0.28,0.06l0.38,-0.75l-0.39,-1.04l0.63,0.28l0.27,-0.24l-0.36,-0.13l-0.24,-0.82l0.71,0.84l0.3,-0.29l-0.65,-1l0.36,-0.14l-0.28,-1.16l0.32,0.25l0.25,-0.24l-0.23,0.8l0.31,0.38l0.24,-1.25l0.22,-0.1l0.06,0.71l0.06,-0.59l0.34,-0.09l-0.34,1.13l0.1,0.19l0.25,-0.72l0.34,0.19l-0.19,0.58l0.43,0.35l0.13,0.63l0.62,-1.48l0.37,0.79l0.31,-0.2l-0.27,-0.41l0.3,-0.21l0.46,0.65l0.4,-0.75l-0.05,-0.92l0.75,-0.31l0,-0.53l-0.16,0.14l0.32,-0.61l0.4,-0.16l-0.36,0.38l0.18,0.32l0.37,-0.51l-0.61,-1.17l0.38,-0.1l0.26,0.74l0.24,-0.3l0.16,0.26l0.45,-1.6l0.42,0.05l-0.25,0.92l0.54,-0.18l-0.04,0.8l0.22,-0.58l0.08,0.63l0.84,-0.3l0.19,0.75l0.65,-0.65l-0.33,1.04l0.31,0.36l-0.03,1.03l0.33,-1.03l-0.2,-0.19l0.85,-0.83l0.32,0.27l-0.42,0.38l-0.04,0.55l0.58,-0.4l-0.18,0.73l0.3,0.49l0.56,-1.34l-0.04,2.61l0.15,-0.69l0.49,-0.4l-0.28,-0.64l0.48,-0.38l0.31,0.81l-0.25,-0.21l-0.14,0.69l0.67,-0.15l-0.57,2.21l0.81,-1.67l-0.5,2.63l0.3,-0.11l0.22,-0.91l0.13,0.63l0.13,-0.37l0.5,0.32l0.1,-1.52l0.22,0.54l-0.3,0.43l0.59,0.55l0.07,-1.42l-0.06,0.46l0.35,0.42l-0.16,0.47l0.62,-0.13l0.09,0.47l0.35,-0.48l-0.14,0.51l0.25,0.16l0.25,-0.47l-0.21,0.81l0.18,0.66l0.37,0.17l0.02,0.92l0.23,-0.24l-0.11,-0.69l0.23,-0.03l-0.05,1l0.18,-0.22l0.14,0.53l0.05,-0.7l0.26,-0.05l0.27,0.54l0.14,-0.76l-0.59,-0.18l-0.17,0.23l0.06,-0.5l0.99,0.25l0.17,-0.32l-0.58,-0.26l0.29,-1.1l0.46,0.55l-0.36,0.32l0.38,0.28l0.61,-0.53l0.03,0.77l0.3,-1.03l0.21,0.03l-0.17,0.54l0.85,-1.39l0.09,0.45l0.37,-0.56l0.37,1.23l0.27,-0.35l0.26,0.09l-0.39,0.74l0.35,0.13l-0.46,1.92l0.43,1.3l0.97,-0.69l1.22,0.04l-0.04,-1.04l0.68,-0.88l0.02,1.18l0.4,0.76l0.43,0l-0.35,-1.13l0.16,-0.18l0.54,0.27l-0.23,-0.32l0.38,-1.72l-0.17,-0.32l0.33,-0.39l1.55,-0.01l0.68,0.32l0.63,0.93l-0.27,0.7l0.24,0.38l0.27,-1.03l0.47,0.49l0.91,-0.35l1.72,0.13l0.03,0.33l-0.93,0.89l0.19,0.32l0.78,-0.43l0.21,0.39l1.2,-0.19l-0.74,1.39l1.04,-1.13l-1.11,1.45l0.33,0.3l0.98,-0.54l0.83,0.04l0.56,-0.32l0.83,0.69l-0.4,0.27l0.43,0.13l-0.01,0.65l-1.04,0.64l0.27,0.26l-0.51,0.21l0.54,-0.1l0.38,0.5l2.29,-0.29l0.84,0.68l-0.28,0.01l0.33,0.27l-0.84,0.93l0.6,-0.42l0.3,0.25l-1.07,1.46l0.56,-0.3l-0.03,0.4l0.47,-0.53l0.42,0.64l0.03,0.78l0.88,-0.96l0.66,0.17l0.4,0.61l0.22,-0.16l0.43,0.45l-0.17,0.17l0.38,0.78l-0.19,0.44l0.32,-0.26l0.35,0.74l0.46,-0.39l-0.12,0.34l0.37,-0.11l0.02,0.7l0.54,0.39l-0.46,0.43l0.43,0.17l-1.67,0.08l-1.02,-0.28l-0.28,-0.77l-0.27,-0.12l-0.07,0.25l0.16,0.85l1.6,1.17l0.21,0.72l0.38,0.18l-0.7,0.28l-0.22,0.56l0.33,0.81l0.91,0l-0.26,0.34l-0.9,-0.07l-0.01,0.72l-1.22,0.16l0.67,0.64l0.54,-0.18l-0.01,0.26l-0.5,-0.04l0.32,0.33l1.04,0.05l0.5,0.59l-0.11,0.93l-0.5,0.68l-1.47,-0.62l0.57,0.56l-1.25,-0.52l-0.15,0.21l0.31,0.27l-0.28,0.18l0.46,0.4l-2.23,-0.04l0.1,0.62l-0.46,-0.02l0.4,0.79l-0.42,0.05l0.04,0.52l0.41,-0.05l0.69,0.66l-0.21,0.52l1.46,-0.43l2.14,0.84l-0.2,0.05l0.37,0.33l-0.13,0.32l-0.53,0.3l0.91,0.34l-0.39,0.38l0.6,0.18l-0.21,0.33l0.25,0.19l-0.3,0.04l0.34,0.14l0.02,0.46l-1.05,0.15l0.35,0.36l-0.52,0.47l0.61,-0.19l0.17,0.86l-0.24,-0.45l-0.26,0.34l0.16,0.25l1.1,0.41l-0.81,0.2l-0.7,1.07l0.1,0.52l1.04,-0.47l0.24,0.42l-0.42,-0.05l0.31,0.32l-0.26,0.39l-0.32,-0.21l0.1,0.3l-0.47,0.5l-0.86,-0.65l0.63,0.66l-1.17,0.67l-0.82,-0.15l-0.29,0.41l-0.62,0.1l-0.64,-0.88l-0.21,0.03l0.13,0.48l-1.47,-0.03l-0.1,0.57l0.25,0.15l-0.31,-0.04l-0.28,0.65l1.65,1.74l-0.86,0.24l-0.51,-0.36l-0.44,-0.59l-0.19,-1.13l-0.35,0.1l-0.21,0.95l0.52,1.54l0.8,0.69l0.42,2.28l0.3,0.39l0.96,0.22l0.41,0.59l0.07,-0.4l1.4,-0.72l0.64,-1.04l-0.64,-1.72l-0.53,-3.05l1.51,3l0.35,1.02l-0.07,0.88l1.76,2.26l-0.86,-0.49l-1.04,-0.11l-2.96,1.04l-0.53,0.88l0.37,0.11l0.2,0.56l-0.15,0.8l0.67,0.13l0.32,-0.41l1.32,-0.13l0.72,1.68l0,1.26l-0.34,-0.16l0.31,0.35l-0.3,0.14l0.6,-0.24l0.75,3.75l1.99,1.79l0.27,1.52l0.61,0.72l-0.24,0.4l0.42,-0.17l0.88,0.31l-0.02,0.35l0.43,-0.38l0.39,0.54l0.25,-0.06l0.88,2.13l-0.26,0.57l0.76,1.05l0.65,0.15l0.75,-0.31l0.15,1.17l0.54,0.31l0.92,-0.32l0.34,-0.6l-0.14,-1.34l0.31,-0.43l-0.1,0.87l0.88,3.13l-0.18,0.38l0.85,1.25l0.97,-0.26l1.41,-1.36l2.12,-3.12l0.64,-2.2l-0.04,-2.36l0.5,-0.4l1.22,-3.08l0.4,-2.96l1.33,-5.13l2.29,-5.35l0.84,-1.22l0.63,-0.35l0.78,0.08l1.05,-0.55l0.82,0.09l1.35,1.86l0.05,0.87l-0.56,-1.24l-1.16,-1.1l-0.74,-0.04l-0.78,0.53l0.28,0.25l-0.31,0.39l-0.71,-0.35l0.25,1.81l-0.44,0.88l0.25,0.86l1.21,0.56l1.35,2.87l1.07,1.51l1.75,1.73l1.54,1.01l3.68,1.28l1.63,0.01l1.54,-0.63l0.94,-1.51l1.47,-1.32l1.05,-0.33l2.24,-1.72l-0.09,0.22l1.12,-0.63l0.85,0.25l1.03,-0.38l4.44,1.48l-0.16,0.14l0.44,0.58l0.7,0.36l0.4,-0.27l0.93,0.08l1.89,2.49l1.53,0.31l1.07,0.74l-0.28,0.55l0.7,-0.43l-0.19,0.64l0.54,-0.45l-0.49,1.29l0.33,-0.05l-0.13,0.74l0.41,-0.1l0.08,0.53l0.41,0.11l0.22,-0.51l0.49,-0.17l-0.16,0.44l0.9,0.04l0.01,0.32l0.99,0.62l0.49,0.05l0.75,-0.62l-0.07,-0.83l-0.97,-0.26l-0.02,-1.44l-0.48,0.08l0.03,-0.4l-0.4,0.31l-0.01,-0.47l-0.32,0.24l-0.22,-0.28l0.66,-0.1l0.47,-0.62l1.13,-3.86l1.24,-0.28l0.85,0.16l0.19,1.25l0.28,0.01l0.34,-0.47l0.61,0.13l-0.03,-0.34l0.34,0.02l-0.6,-0.92l0.14,-0.25l1.6,-0.54l1.01,1.02l1.02,0.17l0.12,2.94l0.62,1.08l0.94,-0.27l0.22,0.23l0.61,-1.96l1.61,0.32l0.56,0.9l0.15,-0.47l0.34,-0.03l0.04,0.34l0.56,-1.41l0.36,0.56l0.09,-0.38l0.17,0.2l0.31,-0.31l-0.16,-0.26l0.34,0.02l-0.71,-0.29l-0.17,-0.55l-0.16,0.15l-1.28,-3.35l-0.02,-2.36l0.26,-0.02l-0.27,-0.13l0,-0.79l0.54,-0.27l-0.04,-0.26l-0.56,-0.26l-0.34,-1.18l-2.37,-0.76l1.57,0.32l0.71,-0.23l0.56,-1.25l0.04,-1.09l0.97,-1.1l0.36,-1.43l0.32,-0.29l0.89,0.75l1.12,-0.86l-0.34,-0.91l-1,-0.3l-1.92,0.2l-0.84,-0.25l-0.74,0.2l-1.4,1.73l-1.54,-0.72l-0.24,-2.4l0.73,-1.87l2.44,-3.1l1.9,-0.2l1.76,0.58l0.43,0.59l0.77,-0.61l2.22,-0.1l1.81,-1.04l0.93,0.31l-0.26,-0.48l0.53,-0.78l1.51,-0.64l0.31,0.06l-0.08,0.27l0.33,-0.19l0.07,-0.29l-1.07,-0.3l0.11,-0.28l-0.35,-0.18l0.19,-0.61l-1.05,-1.46l-0.17,0.11l-1.01,-2.13l-0.55,-0.22l0.19,-0.33l-0.36,-0.38l-0.13,-1.11l1.06,-0.07l1.92,0.62l1.16,0.01l0.77,0.42l0.32,0.75l1.26,1.03l2.37,1.01l5.12,0.57l6.24,0.19l1.6,0.67l3.55,0.33l4,1.32l5.61,1.19l3.48,1.43l5.15,2.7l0.58,0.43l-0.02,0.73l0.86,0.56l4.35,-0.79l2.67,0.33l1.02,-0.23l2.37,0.2l6.35,2.79l2.3,1.8l2,2.48l0.87,2.01l0.24,1.62l-0.31,0.7l-3.13,1.96l-0.45,-2.04l-0.2,0.79l-0.31,-0.03l0.36,-0.69l-0.34,-1.13l-0.39,-0.28l-0.76,0.23l0.46,0.35l-0.45,0.31l-0.04,0.46l-0.31,-0.24l-0.2,0.19l-0.6,1.4l-0.68,0.35l-0.29,0.55l-0.15,0.47l0.45,0.9l0.34,-0.6l0.77,0.55l0.65,-0.43l0.97,1.08l0.91,0.11l1.89,-0.22l0.55,-0.43l1.07,0.72l0.13,0.46l0.6,0.21l-0.1,0.67l0.45,0.35l0.04,0.9l0.83,0.26l2.03,-0.14l-0.51,0.35l0.99,0.23l-0.06,2.13l0.6,0.91l2.37,-0.81l0.37,0.57l2.97,1.16l1.86,2.73l-0.41,-0.05l0.67,1.61l0.71,0.83l-0.05,0.4l1.27,1.61l-0.2,0.44l-0.31,-0.26l-0.98,0.28l-1.46,-0.23l-0.04,0.29l0.75,0.54l1.14,0.11l2.01,1.78l2.15,0.92l3.09,-0.08l1.79,-0.45l0.3,0.27l0.29,-0.42l1.93,-0.45l0.43,0.09l0.06,0.46l0.49,-0.46l0.68,0.2l0.96,-0.86l2.83,-1.24l4.4,-1.14l1.15,-0.57l1.56,0l1.53,-0.7l0.57,0.19l2.92,-0.63l3.84,0.19l0.47,-0.38l0.34,0.23l1.54,-0.23l3.09,0.46l5.82,1.54l3.97,1.68l3.05,1.94l3.23,2.93l2.19,3.39l1.11,3.25l0.53,2.83l-1.04,2.54l0.05,1.22l-0.61,1.27l0.01,0.77l-1.46,2.3l1.26,2.04l2.36,1.82l-0.3,-0.55l0.64,0.06l2.81,1.42l0.31,-0.36l2.09,0.73l0.31,1.74l-0.32,1.88l0.4,4.23l0.55,0.3l0.52,-1.46l-0.66,-1.96l0.03,-1.01l2.73,-2.54l0.46,-0.13l0.54,0.29l0.28,-0.41l-0.24,1.41l0.28,0.81l-1.18,1.19l-0.84,0.42l-0.26,-0.56l0.22,1.13l0.89,-0.02l0.03,-0.29l0.77,-0.2l0.63,-1.2l0.98,-1.02l1.55,-0.45l0.14,-0.85l1.17,-0.72l-0.03,-0.76l0.35,0.22l0.61,-0.16l0,0l0.09,0.84l-0.53,1.53l-0.71,0.35l0.75,1.11l-0.27,1.03l0.92,0.46l0.09,1.54l2.13,2.73l0.04,0.59l-1.44,0.33l-0.48,2.99l0.43,0.81l1.23,0.48l0.73,1.57l-0.7,1.24l-0.89,0.58l0.09,1.12l0.81,0.63l-0.35,0.92l0.11,0.84l-0.88,0.54l0.09,1.88l-0.42,0.77l0.05,1.63l-0.58,0.98l-2.7,-1.26l-4.42,-1.35l-1.02,0.23l-2.26,2.06l-1.54,0.62l-5.34,-0.55l-0.74,0.19l-0.55,0.59l-0.48,1.16l-1.11,-0.51l-0.41,0.3l-0.72,-0.03l-0.61,-0.69l-2.78,2.4l-2.65,-0.16l-1.31,0.96l-0.63,2.5l-1.07,1.39l0.4,0.98l0.91,0.48l0.07,0.37L994.3,450l-0.99,0.43l-0.9,-0.16l-1.15,0.28l-0.37,2.55l0.15,1.71l0.84,1.53l-0.2,2.15l0.21,0.53l1.33,0.42l1.38,1.87l1.25,0.2l2.18,1.09l0.25,1.13l-0.3,1.69l1.14,1.45l0.15,0.63l-1.09,0.62l-0.47,0.96l0.07,0.88l-1.26,1.86l-0.27,1.17l-0.85,0.6l0.29,1.18L996.22,475.53zM870.23,253.26l-0.31,-0.23l0.98,0.24l-0.17,0.32L870.23,253.26zM908.52,279.91l-1.2,-1.39l1.01,-1.67l-0.56,-3.27l0.96,-1.58l0.38,-1.47l-0.19,-1.37l0.62,-1.37l1.45,1.13l0.51,1.22l-0.76,2.01l0.63,1.17l0.13,0.93l1.9,1.25l1.02,-0.03l1.08,-0.86l-0.37,-0.26l-0.44,0.41l-0.53,-0.09l1.17,-1.02l0.54,-0.77l-0.18,-0.16l0.77,-0.31l0.5,0.26l0.78,-0.63l2.81,1.42l2.7,-0.32l1.28,0.89l0.12,0.57l-0.59,1.44l0.33,1.11l-0.14,0.64l0.31,0.14l0.29,1l1.28,0.06l4.04,-1.92l2.73,1.03l0.1,0.44l0.24,-0.29l2.57,0.46l1.02,1.02l0.17,0.54l-0.52,0.27l0.08,0.25l0.54,-0.13l1.49,1.18l2.07,-1.42l1.11,0.41l-2.06,3.74l0.28,1.08l-0.49,2.52l-4.12,1.4l-1.27,0.76l-1.09,0.17l-0.79,0.56l-2.97,0.82l-1.69,0.1l-1.74,-0.56l-0.22,0.34l-3.58,-1.08l-1.1,-0.93l-2.89,-4.06l-2.23,-0.64l-1.84,-0.93l-2.53,-2.63l-1.74,-1.18L908.52,279.91zM843,273.96l-0.21,-1.48l0.76,-0.64l0.18,-0.77l-0.58,-1.2l0.47,-0.17l-0.45,-0.18l-0.22,-0.51l0.78,-0.79l-0.36,-0.66l0.12,-0.53l-0.6,-0.12l-1.11,0.93l1.03,1.13l-0.23,0.42l-0.79,-0.84l-0.22,-0.71l1.04,-0.75l0.59,-1l-0.51,-2.01l0.51,-1.06l0.89,-0.27l0.92,0.45l0.97,-1.24l-0.85,-1.78l-0.21,0.6l-0.26,-1.67l0.32,-1.43l1.25,-1.55l0.69,-0.28l0.71,0.26l0.59,-0.39l1.35,0.03l0.65,-1.73l-0.1,-0.87l0.45,-0.71l0.65,-0.33l0.52,1.55l0.36,0.04l0.39,-2.47l2.25,-1.34l0.37,0.02l0.18,0.52l0.36,-0.4l1.35,-0.15l-0.71,0.38l0.11,1.71l0.55,0.46l-0.61,0.61l0.62,-0.39l0.79,1.11l1.3,0.57l1.35,2.04l2.76,1.08l-0.57,1.31l-0.1,-0.36l-0.46,0.08l-0.13,1.08l0.71,0.37l0.12,0.57l1.06,0.67l0.62,0.84l0.19,-0.38l0.69,-0.16l1.39,0.8l0.35,0.93l-0.05,0.83l-0.43,0.47l0.34,1.13l0.3,0.11l0.32,-0.39l-0.35,-0.92l1.09,0.12l0.84,0.93l0.11,0.85l0.46,0.43l1.06,-0.25l-1.09,-1.94l-0.15,-1.98l0.53,-2.59l-0.33,-0.93l0.1,-1.58l0.85,-3.36l1.8,0.14l2.97,1.63l-0.83,-1.12l-1.24,-3.5l-0.58,-0.09l0.15,-0.54l0.25,0l1.5,1.4l1.36,0.5l1.91,2.85l1.29,0.99l1.03,1.29l0.4,1.25l1.6,1.38l3.24,1.44l1.38,-0.56l0.26,0.2l0.43,-0.81l1.23,-0.42l3.41,1.45l1.98,2.43l0.94,0.52l1.7,0.29l0.65,1.21l0.69,0.61l2.4,1.46l1.22,1.81l0.08,0.58l-1.64,-0.15l-2.24,2.05l-0.57,1.57l0.48,2.28l0.92,0.55l-1.31,0.93l-0.46,2.56l-2.41,2.75l-1.48,0.35l-1.06,0.86l-0.62,-0.22l-0.13,-0.99l-0.37,-0.33l-1.91,-0.22l-0.75,0.34l-0.27,1.54l0.69,-0.09l0.99,1.32l-0.11,0.63l-1.04,0.98l-0.86,0.32l-1.22,-0.22l-1.5,0.55l-0.15,-0.43l-0.32,-0.05l-0.43,0.63l-0.33,-0.17l0.03,0.27l-0.43,-0.58l-0.57,-0.19l-0.76,1.84l0.61,-0.54l0.06,0.27l-1.24,0.99l-0.97,-0.09l-3.31,-3.2l0.31,-0.17l0.25,-0.95l0.74,-0.27l0.86,0.68l0.38,0.83l0.39,0l-0.07,-0.66l-0.87,-1.02l0.03,-1.07l-1.06,0.55l-1.57,-0.16l-0.67,0.78l-1.16,0.56l-0.24,0.58l-5.42,1.36l-4.36,2l-1.75,0.41l1.01,-0.38l-0.48,-2.03l-1.25,-1.03l0.11,-0.4l-0.42,0.07l-0.29,-0.61l-0.47,-0.2l-0.27,0.23l-0.08,-0.46l-0.83,1.45l-0.47,-0.03l0.35,0.32l-0.03,1.53l0.41,0.38l0.76,-0.78l0,0.33l-0.78,0.81l-0.99,3.29l-0.99,1.22l-1.12,0.67l-0.74,-0.09l-2.53,-2.06l-3.75,-1.18l-1.32,-2.16l-0.82,-2.49l0.33,0.03l0.21,-0.4l-0.59,0.16l-1.25,-1.48l0.16,-0.48l-0.21,-0.16l0.51,-0.55l-0.97,0.73l-1.95,-1.5l-2.53,-4.85l0.9,0.54l-0.11,-0.23l-1.11,-0.78l-0.19,-2.63l0.95,-0.74L843,273.96z"
},
{
"id":"RU-SAK",
"title":"Sakhalin",
"d":"M907.27,759.55l1.22,1l1.65,-0.33l-0.58,0.98l-0.44,-0.23l-0.96,1l-1.31,0.11l-0.47,0.8l-0.9,0.47l-0.32,1.15l-0.41,-0.03l-0.29,0.91l-1.37,0.65l-0.22,1.38l-0.9,0.08l-0.21,-1.2l2.42,-2.09l0.02,-0.54l1.76,-2.17l0.64,-1.51L907.27,759.55zM926.05,749.05l0.75,0.45l-0.49,0.67l0.37,0.52l-0.25,0.58l-1.6,0.04l-0.89,0.78l-1.31,0.38l-1.53,1.07l-1.4,1.55l-0.86,0.14l-0.45,-0.58l-0.5,0.11l-0.29,0.52l0.29,0.24l-0.4,0.68l-1.87,1.38l-0.92,1.47l-0.89,0.07l-0.88,1.32l-0.7,-0.14l0.08,-0.56l0.56,-0.5l-0.04,-0.81l0.34,0.54l0.29,-0.43l-0.18,-0.44l0.63,0.23l0.65,-0.62l0.06,-0.58l-0.6,-0.21l-0.04,-0.45l0.9,0.18l0.22,-0.64l1.73,-1.22l0.2,-0.82l-0.21,-0.47l1.08,0.4l0.56,-1.17l0.98,-0.32l-0.16,-1.44l0.38,-0.64l0.46,0.1l0.64,1.64l1.26,-0.07l1.65,-0.96l0.17,-0.59l1.23,-1.24L926.05,749.05zM938.67,742.28l-2.38,2.06l-0.17,0.78l-0.47,0.51l-0.75,0.66l-0.71,0.11l-1.83,1.94l-1,0.54l-0.94,-0.06l1.92,-2.75l0.89,-0.14l1.71,-2.23l1.12,-0.28l-0.07,-0.58l0.32,-0.29l0.87,-0.4l0.86,0.27l0.81,-0.29L938.67,742.28zM950.71,732.36l0.42,0.37l-0.85,0.77l-0.11,0.65l-2.39,2.32l-0.44,-0.01l-0.3,-0.8l1.09,-0.04l0.42,-0.91l0.93,-0.56L950.71,732.36zM952.3,730.13l0.63,0.27l-0.17,0.56l-0.61,0l-0.14,-0.53L952.3,730.13zM956.58,725.64l-0.03,0.94l-0.54,0.39l0,-0.8L956.58,725.64zM957.66,722.21l0.53,0.4l0.03,0.53l-0.81,-0.38L957.66,722.21zM964.74,713.78l0.31,0.22l-0.21,0.49l-1.42,1.3l-0.18,-0.33l0.76,-0.54l0.15,-0.97L964.74,713.78zM966.85,710.89l0.86,0.45l-0.06,0.4l-0.65,0.16l-0.35,-0.81L966.85,710.89zM969.48,705.77l0.52,0.29l-0.76,1.59l0.23,1.54l-0.38,0.48l-0.87,0.17l-0.36,-0.23l-0.07,-0.82L969.48,705.77zM978.03,693.1l0.85,0.3l-0.22,1.03l0.33,0.55l-0.01,1.07l-0.96,0.51l-0.09,0.71l-0.97,1.7l-0.49,0.16l-0.19,0.47l-1.28,0.06l-0.76,0.5l-0.85,1.56l-0.29,-0.61l-0.89,0.04l0.25,-1.76l-0.35,-0.98l0.96,0.13l0.45,-0.76l1,-0.13l0.24,-0.29l0.48,0.12l0.78,-0.85l0.75,-2.28L978.03,693.1zM981.23,692.03l0.21,1.12l-0.72,1.45l-0.98,0.03l-0.68,-0.57l0.12,-0.95L981.23,692.03zM882.44,650.03l2,3.79l-0.05,0.95l-0.63,1.04l0,0.97l2.29,6.85l0.75,4.59l-0.01,3.98l-0.24,1.53l-0.8,1.48l-0.44,3.27l0.3,0.82l-0.31,-0.09l-0.02,0.62l0.35,0.22l-0.03,0.45l0.46,0.24l0.12,-0.22l0.56,1.42l-0.67,1.54l0.21,0.39l-0.28,0.81l0.99,0.05l0.11,-1.49l0.83,3.34l-0.22,-0.32l-0.51,0.2l0.88,0.72l0.21,0.64l1.7,9.66l1.7,4.03l0.01,0.76l0.91,2.31l0.05,1.4l0.75,1.21l-0.13,0.88l0.44,1.99l0.77,2.21l2.18,1.99l-0.13,1.47l0.54,0.87l-0.55,0.03l-0.13,-1.44l-0.62,-1.23l-1.65,-1.59l-1.42,-2.03l-2.97,-0.96l0.2,-0.06l-0.3,-0.24l-1.08,-0.24l-0.45,0.17l-0.66,-0.72l-1.21,0.28l0.7,0.4l-0.26,0.29l1.02,0.03l-1.89,0.73l-1.48,1.53l-0.16,0.83l0.26,1.45l-1.27,2.62l-1.53,5.03l-0.57,3.14l0.08,1.02l1.14,3.11l1.84,1.61l0.59,1.11l0,1.84l0.53,1.72l0.43,0.36l-0.05,0.4l-0.41,-0.22l-0.15,0.49l0.45,0.2l0.25,0.88l0.62,-0.09l0.71,0.37l0.24,-0.37l-0.28,-0.38l-1.08,-0.28l-0.24,-0.38l1.67,0.26l0.26,-0.56l0.26,0.12l0.54,3.69l0.55,1.13l-1.11,1.92l0.02,0.91l-0.37,0.8l0.06,-1.92l-0.86,-3.15l-1.15,-1.01l-0.55,0.13l-1.23,-0.39l-0.85,0.28l-0.32,-1.39l-0.31,-0.18l-0.04,0.27l-1.15,0.35l-0.76,0.97l-1.19,3.37l-0.51,2.6l-0.6,0.45l-0.12,0.92l-1.18,-1.57L876,738.3l1.28,-3.13l0.53,-2.18l-0.14,-1.11l-0.56,-0.9l0.24,-0.75l-0.27,-2.66l0.9,-2.58l0.83,-1.29l-0.43,-3.65l-1.82,-3.46l-0.31,-1.33l0.95,-1.19l-0.15,-0.5l0.33,-0.26l0.19,-2.2l0.39,0.12l-0.23,-0.28l0.29,-0.68l-0.18,-1.27l0.54,-1.97l0.17,-3.15l-0.25,-1.63l0.31,-1.1l-0.34,-2.74l0.18,-0.8l-0.78,-2.09l0.3,-3.04l1.05,-2.03l0.16,-1.3l-0.6,-2.34l-0.64,-0.88l0,-0.82l-1.17,-1.21l0.25,-0.35l-0.18,-0.26l-0.28,0.28l-1.55,-1.62l0.76,0.36l0.35,-0.82l-0.48,-0.68l-0.96,-0.51l0.42,-0.75l-0.37,-1.76l0.44,-0.67l-0.47,-1.91l0.17,-0.82l0.73,-0.69l0.52,-1.22l-0.07,-1.94l0.72,-3.66l-0.65,-1.59l-0.46,-2.58l0.89,-0.75l2.62,-1.19l-0.27,0.16l0.19,1.69l0.22,0.25l0.55,-0.29l0.67,0.1l1.07,-1.72l0.59,0.17l-0.1,-0.55l-0.21,0.1l-0.47,-0.65l-0.35,0.65l-0.26,-1.38l1.16,-0.34l0.25,0.9l0.83,-1.12l-0.23,-1.3l-0.38,-0.3l-0.24,1.37l-0.58,0.42l0.71,-1.98l0.05,-1.07l-1.82,-2.25l-0.5,-1.34l-0.82,-0.8l0.9,0.3l1.04,-0.26l0.87,-0.56l0.08,-0.8L882.44,650.03z"
},
{
"id":"RU-SMO",
"title":"Smolensk",
"d":"M84.72,633.44L85.62,633.88L86.6,633.83L87.95,634.8L88.02,634.03L89.3,633.8L89.49,634.51L90.21,634.55L89.56,634.89L90.01,635.22L90.69,634.73L91.44,634.98L91.79,634.61L92.46,634.88L92.57,635.25L92.84,634.4L93.36,634.65L92.95,635.43L93.28,635.53L93.46,635L94.06,635L95.87,635.52L96.27,634.83L96.69,635.28L97.07,634.81L97.44,635.36L97.92,634.36L98.67,633.98L99.58,634.06L100.24,633.59L100.18,632.9L100.7,632.97L101.21,632.23L100.9,631.62L101.18,631.07L101.33,631.43L101.62,631.22L101.93,631.47L101.96,631.94L102.22,631.88L102.53,630.9L101.98,630.5L102.47,629.84L103.08,629.76L103.44,630.14L104.99,629.88L105.59,631.19L106.07,630.46L107.03,631.31L108.27,631.76L108.82,630.98L111.25,631.17L111.25,631.17L112.26,633.27L112.61,633.36L112.56,634.98L113.03,635.5L113.07,635.92L112.4,636.14L112.57,637.96L112.17,639.3L112.83,640.04L112.83,640.04L112.85,640.88L112.2,642.03L111.96,642.02L111.47,643.38L111.3,643.51L110.99,642.93L109.33,644.63L109.41,645.23L109.97,645.73L109.78,646.01L107.79,647.14L106.25,646.74L106.96,647.71L106.48,649.15L105.32,648.99L104.85,649.29L104.53,648.69L103.97,648.81L103.08,648.38L102.49,648.42L102.25,648.74L102.05,648.41L101.25,649.17L100.81,649.1L100.5,649.78L100.88,650.04L100.5,650.95L101.15,651.43L100.47,652.42L100.73,652.91L100.22,653.16L99.97,654.33L99.25,654.44L99.68,655.13L99.68,655.13L99.05,655.42L99.25,655.76L98.91,656.1L98.35,655.6L97.81,656.79L98.34,657.46L98,657.85L97.6,657.57L97.45,658.68L97.01,658.56L96.49,659.5L95.4,660.4L95.55,660.86L95.2,661.33L95.17,662.2L94.76,661.93L94.06,662.32L94.06,662.32L94.09,661.67L93.4,661.72L93.22,661.29L93.04,661.65L92.9,661.17L91.83,660.23L91.91,659.59L91.6,659.39L92.26,658.91L91.94,658.4L91.27,658.54L91.06,658.21L90.51,658.15L90.72,657.98L90.21,658.08L90.15,657.77L89.49,657.53L88.13,657.89L86.93,657.68L86.85,657.29L87.55,656.45L87.41,655.98L87.71,655.79L87.44,655.23L87.77,655.05L87.78,654.61L87.03,654.44L87.06,653.92L86.41,653.95L86.2,653.5L85.14,653.19L84.29,652.06L83.81,652.03L83.77,650.85L83.17,649.54L82.05,648.96L82.94,647.17L81.42,646.92L81.47,646.43L79.72,645.35L80.28,643.53L81.04,643.4L80.94,642.54L81.62,642.28L81.33,640.56L80.22,639.12L80.24,638.62L81,637.82L80.77,636.84L81.14,636.6L80.83,636.15L81.14,635.78L80.84,635.03L80.84,635.03L81.57,634.35L81.35,634.09L81.94,633.69L82.41,633.54L83.1,633.86z"
},
{
"id":"RU-SPE",
"title":"Saint Petersburg City",
"d":"M75.49,577.77l0.31,-0.21l-0.01,-1.07l-1.73,-0.47l-0.3,-1.92l-2.25,-0.78l-1.48,0.51l0,0l0.94,-1.34l0.7,-0.15l3.52,1.58l1.82,0.41l-0.23,1.11l1.24,0.93l-0.05,1.93l1.73,1.06l0.09,0.47l-0.64,0.71l-0.82,-0.01l-0.39,0.88l-1.08,0.4l-0.9,-0.15l-1.25,-1.05l-1.53,-1.67v-0.32l-0.48,0.05l-0.77,-0.55l0.14,-0.99l0,0l0.61,0l1.78,1l1.07,-0.1L75.49,577.77z"
},
{
"id":"RU-SAR",
"title":"Saratov",
"d":"M206.1,669.54L206.21,669.91L205.49,671.07L205.69,671.59L206.71,670.8L207.39,670.97L207.8,671.47L208.29,671.42L208.86,672.29L210.24,673.39L212.65,673.18L213.39,673.6L213.25,674.14L213.88,674.77L214.39,674.88L214.53,674.28L214.89,674.24L215.32,674.71L215.42,675.89L216.7,676.79L217.8,676.82L218.28,677.29L219.25,677.49L219.06,677.79L219.86,678.67L220.37,678.49L222.38,679.17L223.87,681.37L223.87,681.37L223.68,681.93L223.68,681.93L222.95,681.88L222.97,682.61L223.37,682.92L223.09,683.88L222.45,683.95L222.82,683.29L222.15,683.14L221.75,683.13L221.37,683.61L221.35,685.06L221,685.06L220.98,685.47L220.19,685.54L220.31,686.6L217.21,687.82L215.79,689.18L214.12,689.25L213.52,689.01L212.83,690.51L213.45,692.09L211.17,692.94L209.25,695.01L207.88,694.3L207.34,694.47L208,695.32L208.36,698.49L208.93,699.72L208.75,700.5L209.45,700.77L209.63,701.47L208.61,702.54L206.44,703.53L206.38,703.87L205.57,703.19L204.99,703.2L204.03,700.71L203.27,700.07L202.02,698.03L200.12,696.56L199.28,697.3L199.28,697.3L198.27,697.39L197.75,696.34L196.74,696.58L195.69,695.64L195.15,694.55L193.83,693.97L193.45,694.17L193.26,695.08L192.54,695.69L191.54,695.38L190.21,696.02L189.91,695.67L190.01,694.44L188.23,693.15L187.64,693.09L186.98,693.59L187.5,694.9L187.25,695.28L185.06,695.09L183.93,695.53L183.46,694.06L184.24,693.38L184.41,691.72L182.61,689.12L181.76,689.05L181.08,688.39L179.79,688.36L179.28,688.85L178.65,688.19L177.05,688.33L176.06,689.27L175.23,689.5L175.02,689.25L175.26,688.57L175.02,688.4L174.03,689.06L173.39,688.91L171.12,690.29L170.3,689.98L167.14,687.6L167.14,687.6L167.04,686.03L166.69,685.4L166.36,684.98L164.98,684.55L164.47,683.93L164.47,683.93L164.22,683.29L164.36,682.64L165.58,680.81L165.59,680.04L166.45,678.27L166.42,677.58L167.34,676.04L167.58,674.93L168.31,674.36L168.31,674.36L169.04,673.74L169.52,673.71L170.84,674.85L171.5,674.31L173.33,673.8L174.41,674.62L175.88,674.83L176.86,675.57L178.55,674.25L178.87,673.04L179.17,673.03L179.88,673.52L181.04,673.57L182.37,675.07L182.86,674.25L183.33,674.05L185.64,674.16L186.7,672.93L189.14,674.26L189.38,673.89L189.01,672.87L189.88,672.47L190.38,671.77L191.2,671.8L191.83,670.86L192.61,670.97L193.64,670.42L193.94,671.21L194.75,671.48L194.75,671.48L195.2,671.82L196.32,671.43L196.74,672.22L197.55,671.89L197.91,672.26L199.23,672.45L200.45,671.62L201.73,672.21L202.1,671.92L201.72,670.97L202.25,670.16L202.93,670.69L203.51,670.54L203.95,669.64L204.61,669.78L205.44,669.22z"
},
{
"id":"RU-STA",
"title":"Stavropol'",
"d":"M158.33,744.39L160.06,744.51L161.36,745.16L161.64,745.04L161.5,744.27L161.93,743.85L161.73,743.12L162.09,743.07L162.81,743.28L162.67,744.78L164.36,744.56L165.29,743.73L166.14,743.55L167.09,742.17L167.79,742.86L170.11,743.81L171.03,744.71L172.72,744.88L175,745.76L176.2,747.98L177.75,749.63L180.91,750.5L181.47,751.11L185.12,752.8L185.95,753.39L186.91,754.8L186.91,754.8L186.06,755.87L186.45,756.96L186.12,757.71L185.44,758.74L184.04,759.47L184.2,760.1L183.96,760.41L185.21,760.69L185.29,761.69L184.99,762.18L183.45,762.64L183.25,763.04L184.39,763.58L185.32,763.19L185.88,763.4L185.91,764.96L185.91,764.96L185.52,765.29L185.56,766.22L185.03,766.59L183.98,766.56L183.7,765.74L182.85,765.95L182.69,767.84L181.87,768.38L181.54,768.24L181.54,768.24L180.74,767.25L179.76,767.09L178.03,767.6L177.7,767.38L177.7,767.38L177.72,766.68L178.43,765.74L178.39,765.21L177.49,766.34L175.18,765.46L174.43,766.02L173.83,767.29L172.31,766.85L170.9,767.27L170.17,765.9L169.62,766.38L166.62,767.19L166.62,767.19L166.23,766.94L166.12,765.93L165.57,765.01L165.05,764.88L165.14,765.42L164.78,765.61L163.59,764.92L163.88,763.87L166.26,762.57L165.51,761.41L165.2,761.49L165.13,762.09L164.42,762.04L164.38,762.54L163.59,761.72L161.26,761.27L160.53,760.07L159.75,759.99L159.38,760.31L159.38,760.31L159.38,760.31L159.38,760.31L157.34,758.87L156.8,757.93L157.58,757.64L158.5,756.5L158.43,755.5L157.03,754.74L156.14,753.52L156.16,752.63L153.7,752.33L153.42,750.47L152.74,749.42L152.03,748.97L152.26,747.7L153.38,747.47L154.13,747.82L154.62,746.9L155.18,746.9L154.98,745.92L154.3,745.39L154.46,744.65L154.46,744.65L156.03,744.98L156.5,744.31z"
},
{
"id":"RU-SVE",
"title":"Sverdlovsk",
"d":"M285.55,547.43L285.96,547.02L289.03,548.37L289.31,548.78L289.29,550.31L289.88,550.98L292.43,550.44L297.83,551.41L308.88,558.63L310.15,560.55L310.29,561.4L309.71,563.31L310.47,565.95L312.98,570.45L313.24,571.58L312.76,572.71L315.95,574.03L316.44,574.95L317.01,578.26L317,582.18L317.53,583.29L318.35,584.17L319.22,584.54L321.46,584.6L324.31,585.55L325.98,585.48L326.29,586.75L327.02,586.69L327.24,586.98L329.11,592.94L330.47,594.47L331.97,595.01L332.24,596.26L332.24,596.26L332.68,600.3L333.87,603.12L331.59,604.41L331.21,605.06L330.45,605.31L329.99,606.12L329.11,606.77L328.19,606.11L324.46,608.19L325.32,609.21L324.35,610.86L325.9,617.68L326.11,618.05L327.07,617.9L327.23,618.19L326.73,619.66L325.01,619.96L325.01,619.96L324.14,619.09L322.26,619.06L321.26,620.1L320.77,620L320.48,620.27L320.54,621.43L319.48,622.36L319.65,623.51L318.88,623.78L316.54,623.5L314.45,621.88L313.67,622.23L313.3,622.82L313.05,622.48L311.78,622.57L310.51,621.91L309.08,622.75L308.38,623.6L307.73,622.52L307.39,622.5L306.59,623.09L304.88,625.82L304.03,626.39L303.95,627.97L303.95,627.97L302.9,627.52L302.51,626.61L301.73,626.33L301.64,625.83L300.4,625.89L299.7,625.12L298.88,625.4L298.02,625.01L297.06,625.77L297.56,627L294.96,627.27L294.36,626.94L293.52,627.19L292.33,626.47L290.29,627.02L289.13,626.61L287.39,627.03L286.71,625.93L284.96,625.75L284.15,625.29L283.35,625.71L283.51,626.95L282.99,627.35L282.58,627.24L282.43,628.28L282.43,628.28L281.67,629.23L280.9,629.09L279.07,627.89L277.31,628.87L277.01,628.52L276,628.38L275.14,628.93L274.69,628.85L273.63,628.08L272.97,628.04L271.89,628.52L271.44,628.05L271.72,627.4L271.01,626.55L270.86,625.87L270.86,625.87L270.61,622.64L271.04,621.53L269.73,619.41L269.92,618.29L270.47,617.83L272.13,618.5L272.83,618.17L274.71,616.02L275.08,616.05L275.43,616.55L275.71,616.36L275.43,615.8L275.69,615.5L275.03,614.57L275.36,613.29L274.39,612.51L274.31,611.98L275.04,610.34L274.84,609.48L275.52,608.59L275.53,607.93L276.17,607.24L277.18,607.65L278.43,607.55L278.91,609.09L279.94,607.85L281.32,606.84L281.39,605.56L281.12,605.09L279.97,604.82L279.42,604.02L279.33,602.71L280.46,601.39L280.86,600.4L282.2,599.29L283.17,599.47L283.58,599.19L283.92,598.12L285.29,597.19L285.63,596.54L285.18,594.74L285.48,593.94L285.31,593.69L284.22,593.88L283.72,593.5L283.47,592.7L282.99,592.54L283,591.32L283.76,590.19L283.18,589.18L283.34,587.9L282.13,586.33L281.11,586.22L280.35,585.76L279.35,584.08L278.55,583.39L279.56,579.93L280.61,578.27L282.71,576.39L283.84,572.53L283.76,571.13L285.12,567.91L285.81,565.08L285.82,562.76L284.91,560.98L284.43,557.66L284.42,556.5L285.78,553.03L285.05,551.21L285.05,551.21L284.86,548.82z"
},
{
"id":"RU-TAM",
"title":"Tambov",
"d":"M147.38,663.47L148.09,663.6L148.34,662.68L148.73,663.12L149.68,662.58L149.44,661.78L149.92,661.46L150.48,662.16L150.44,661.55L150.99,661.43L151.18,660.78L151.75,660.82L152.15,661.69L152.39,661.79L152.81,661.3L153.87,661.76L154.18,662.46L154.63,662.52L154.84,661.65L155.21,661.84L155.58,661.63L155.42,661.14L155.89,661.03L156.24,658.41L157.23,658.38L157.47,657.75L157.62,658.19L158.81,657.84L158.97,658.13L159.81,657.81L161.13,657.88L161.13,657.88L161.39,658.11L161.19,661.19L162.53,662.04L162.37,663.19L162.67,663.48L163.48,663.52L164.61,665.08L164.55,665.91L167.35,668.4L169.47,671.09L169.51,671.84L168.34,673.18L168.31,674.36L168.31,674.36L167.58,674.93L167.34,676.04L166.42,677.58L166.45,678.27L165.59,680.04L165.58,680.81L164.36,682.64L164.22,683.29L164.47,683.93L164.47,683.93L163.79,683.59L163.21,683.95L162.65,682.82L161.96,682.77L161.74,683.56L161.21,683.2L160.36,683.19L159.67,682.4L158.99,682.63L157.96,681.98L156.1,681.66L155.49,682.38L153.67,682.56L153.2,682.21L153.39,681.02L153.13,680.54L150.32,679.74L150.32,679.74L150.99,677.44L151.7,677.09L151.74,676.44L150.28,675.19L148.94,674.8L148.61,674.38L148.84,673.81L146.81,672.71L146.03,670.63L146.39,669.86L147.02,669.93L147.28,669.61L146.79,668.55L147.5,667.66L147.04,667.38L147.22,666.87L146.88,664.96z"
},
{
"id":"RU-TOM",
"title":"Tomsk",
"d":"M397.96,595.13L398.23,594.45L401.8,591.03L401.98,590.14L401.35,587.74L402.87,586.36L403.67,584.57L404.47,584.42L405.35,582.99L408.92,582.37L409.6,576.55L409.28,575.09L410.33,572.98L410.07,571.28L410.27,569.66L411.67,568.77L411.81,568.39L411.3,567L411.76,565.88L411.68,564.73L411.94,564.19L412.39,564.02L413.85,564.59L416.82,564.67L418.65,565.34L419.26,564.73L422.27,565.04L423.33,564.21L423.66,564.89L424.73,565.43L425.71,564.42L426.34,564.47L427.4,564.72L427.8,566.66L428.86,566.91L430.68,566.5L433.95,566.49L435.06,565.71L437.06,565.36L437.99,564.74L438.67,564.79L440.3,565.56L440.55,567.16L443.38,567.45L444.2,567.09L446.16,567.14L448.23,568.86L448.9,568.77L450.02,567.58L450.13,566.11L450.94,565.25L455.71,561.61L458.02,561.44L461.09,564.07L463.29,563.93L463.29,563.93L463.48,564.75L464.33,565.38L467.4,571.36L466.83,572.7L466.17,573.28L466.18,575.37L465.61,576.44L466.1,577.98L472.54,577.81L474.9,577.17L478.17,576.95L482.73,577.83L483.55,578.17L483.88,578.84L484.02,580.87L486.45,580.95L487.96,584.87L489.19,586.89L493.05,586.33L494.1,586.28L494.28,586.6L494.4,587.77L495.77,589.24L495.9,590.09L493.9,591.14L492.35,593.52L489.58,596.73L489.83,600.31L490.6,601.57L490.7,602.5L494.69,603.35L495.45,604.29L496.97,605.01L498.48,604.76L499.12,604.94L499.96,605.78L500.08,606.79L499.93,609.21L497.68,609.93L497.98,611.03L496.47,611.76L495.13,614.82L493.99,615.92L493.85,616.46L495.05,616.32L495.38,617.05L494.56,618.98L494.56,618.98L494.06,620.13L493.1,619.83L490.37,621.58L489.1,622.75L487.47,623.44L487.13,621.95L485.54,622.87L485.61,621.99L484.25,622L484.02,622.99L483.15,623.36L481.64,623.43L481.42,623.17L481.65,622.36L480.18,622.34L478.89,623.17L478.45,623.1L477.49,622.09L477.2,622.32L476.95,623.71L476.39,623.77L475.8,624.46L474.42,625.19L474.06,626.16L472.54,626.65L472.76,627.33L473.16,627.48L470.5,627.7L468.34,628.63L467.25,628.55L464.77,630.01L464.77,630.01L464.06,630.64L463.45,630.71L462.51,629.98L461.26,630.39L460.03,631.9L458.64,634.45L456.31,634.42L455.8,633.74L456.28,633.54L456.84,632.29L456.18,630.31L456.25,629.28L455.52,628.81L455.62,627.83L454.86,627.19L455.96,625.17L455.09,623.52L453.14,624.04L453.16,624.71L452.73,625.24L449.89,625.53L444.39,627.08L443.86,626.92L441.44,623.69L441.01,623.52L437.02,624.57L434.69,624.87L430.88,619.46L429.06,618.58L427.72,617.54L421.95,616.27L421.05,615.28L418.58,615.48L410.51,615.25L409,614.64L407.17,614.84L404.86,614.27L404.86,614.27L403.8,612.18L403.01,612.41L402.83,611.06L401.69,608.91L400.86,608.85L401.17,607.83L400.66,604.76L398.96,603.95L397.61,602.8L397.56,602.25L398.62,601.18L397.2,599.82L397.77,599.04L399.38,598.02L398.09,596.2L398.09,596.2L398.42,595.71z"
},
{
"id":"RU-TUL",
"title":"Tula",
"d":"M126.17,645.04L126.83,645.36L126.86,645.13L127.9,645.26L128.39,645.83L128.55,646.61L128.95,646.42L129.61,646.71L130.17,646.32L130.18,645.24L131.38,645L132.16,646.13L132.08,646.61L132.62,646.75L133.53,647.66L133.88,647.31L134.62,647.67L135.13,647.51L135.33,647.94L135.07,648.75L134.41,648.88L134.81,650.36L135.4,650.99L135.05,651.36L135.19,651.84L136.54,652.44L136.54,652.44L136.72,653.17L137.47,653.47L137.21,654.07L136.63,654.06L136.62,654.72L137.2,654.96L136.99,655.22L137.4,655.41L137.35,655.94L137.62,656.17L138.31,656.04L137.67,656.5L137.8,657.14L137.45,657.39L138.06,657.46L137.82,657.89L138.01,658.28L138.85,658.25L138.39,658.8L138.18,660.53L138.18,660.53L138.15,660.99L137.72,660.7L136.85,661.36L137.34,661.63L137.07,661.76L137.53,662.83L135.48,663.43L136.39,664.94L135.86,665.09L136.74,665.93L136.41,666.58L136.14,666.5L136.17,667.01L135.66,667.07L135.57,666.4L135.28,666.43L134.93,667.34L134.59,667.2L134.57,667.58L133.97,667.81L133.63,666.6L131.73,666.74L131.63,666.46L130.98,666.45L131.04,667.03L130.61,667.04L130.61,667.04L129.62,665.56L129.22,665.97L128.63,665.55L128.62,663.93L126.6,663.61L126.56,664.16L125.89,664.4L124.3,663.68L123.98,663.98L122.67,663.6L122.05,662.57L122.21,662.35L120.88,662.58L119.74,661.73L119.34,660.88L117.98,660.27L117.58,660.39L117.27,659.6L117.27,659.6L117.81,659L116.77,658.14L117.12,657.7L116.76,657.21L117.44,656.82L117.18,656.42L117.75,655.94L118.34,656.07L118.33,655L119.04,654.25L117.64,654.08L118.27,654L118.41,653.71L117.6,653.25L118.78,653.43L119.5,652.46L120.3,652.65L120.93,651.9L121.95,651.61L122.37,651.94L124.32,651.79L124.06,651.41L124.27,650.07L123.55,649.96L123.34,649.24L123.97,648.81L123.72,648.23L124.53,648.02L125.26,648.68L125.79,647.69z"
},
{
"id":"RU-TA",
"title":"Tatarstan",
"d":"M218.2,621.63L218.84,621.89L219.26,621.48L219.81,621.78L220.4,621.16L221.83,623.26L221.71,623.83L222.38,625.15L223.56,625.5L223.36,624.65L223.88,624.37L224.33,624.86L224.58,625.68L224.31,626.85L225.08,628L225.83,628.53L226.36,628.36L227.17,629L227.67,628.98L227.91,628.39L227.91,628.39L229.44,627.95L229.8,628.15L228.7,629.02L227.99,630.12L227.93,630.48L228.59,630.97L229.66,630.49L231.02,630.88L231.84,630.62L232.33,630.7L233.15,631.6L233.52,631.53L233.9,630.97L233.7,629.3L234.64,628.82L235.49,629.84L236.48,629.2L237.03,630.02L237.55,629.6L237.07,628.37L237.29,628.13L238.12,628.53L238.3,628.02L237.73,627.34L236.13,626.74L236.11,626.5L237.32,625.39L238.34,625.15L238.86,624.23L238.61,623.71L239.66,622.91L239.98,623.38L239.19,624.84L239.4,627.17L240.85,628.36L241.51,628.5L241.89,628.01L241.39,626.72L241.63,626.35L243.27,626.97L243.22,628.39L242.25,629.05L242.23,629.91L241.19,630.62L241.05,631.04L241.95,631.86L244.91,630.52L244.91,630.52L245.97,631.02L246.49,632.19L247.02,632.52L246.86,632.75L247.76,633.22L247.8,634.24L246.43,635.49L246.5,636.31L246.05,636.78L245.67,637.99L244.08,638.86L243.02,640.23L242.24,640.21L240.52,640.9L240.23,641.55L241.09,641.82L242.17,642.72L242.87,643.8L243.79,643.76L244.09,644.21L243.48,645.32L243.72,646.56L242.54,648.53L242.25,649.67L241.86,651.94L242.25,653.69L242,654.51L242,654.51L241.78,654.6L240.9,653.57L239.53,654.19L239.65,653.36L238.89,652.92L239,652.43L240.19,652.07L240.29,651.77L239.82,651.12L239.16,651.66L237.74,650.89L236.38,650.92L236.03,650.49L236.03,650.49L235.71,649.68L235.41,649.59L234.89,650.02L234.26,649.68L232.56,651.04L232.43,650.4L231.69,649.86L231.73,649.08L230.89,648.91L229.13,647.88L228.66,647.11L227.85,648.1L227.54,647.95L227.66,646.84L226.98,647.43L226.05,647.04L226.08,647.55L224.89,648.64L224.96,649.81L224.53,650.95L223.14,649.69L221.56,651.13L221.19,650.98L221.35,650.42L220.83,649.57L220.49,649.39L219.92,649.95L219.31,649.06L218.25,648.68L218.25,648.68L216.79,648.72L216.03,647.89L214.67,647.91L214.82,647.41L213.61,645.09L212.46,644.11L212.06,644.54L211.91,644.24L211.64,644.42L211.34,644.95L210.56,645.04L211.45,645.47L210.5,645.53L209.35,647.23L208.47,647.54L207,647.55L206.35,646.86L205.36,646.61L205.35,645.87L204.71,646.04L204.14,645.64L203.67,646.4L202.94,646.28L202.7,647.52L202.25,647.25L202.17,646.2L201.73,645.87L201.22,646.05L201.31,646.59L200.33,647.72L200.49,648.45L200.2,648.6L199.34,648.17L199.05,648.77L198.74,647.62L199,647.31L198.17,646.34L198.17,646.34L199.42,645.82L198.89,645.01L199.37,644.6L199.28,644.18L200.27,644.94L201.42,645.09L201.3,644.39L202.3,644.44L201.94,643.15L204.19,642.76L204.2,642.38L203.26,642.77L202.84,642.21L202.98,641.51L203.93,640.98L203.15,638.99L202.6,638.81L202.66,639.53L202.23,639.48L201.71,640.12L201.26,639.96L201.37,638.93L201.51,638.55L202.29,638.32L203.48,636.56L204.56,635.69L203.77,635.28L203.73,634.61L204.93,634.16L205.46,633.3L206.48,633.09L206.45,632.36L206.45,632.36L206.33,631.54L207.85,630.37L208.28,629L209.17,629.27L209.74,628.15L210.46,628.17L211.03,627.36L211.11,626.96L210,626.94L209.82,626.4L210.35,625.46L211.37,624.83L213.2,625.26L213.68,624.28L214.5,624.39L214.91,623.48L215.96,623.09L216.54,623.43L216.2,623.95L216.5,624.41L217.39,623.8L217.83,624.26L218.34,623.36L219.16,623.04L219.21,622.74L218.94,622.29L218.33,622.21z"
},
{
"id":"RU-TY",
"title":"Tuva",
"d":"M552.24,659.18L552.34,658.29L553.36,658.21L554.14,659.29L554.7,659.43L555.04,659.93L556.19,659.93L556.84,660.57L557.08,661.3L558.13,661.89L558.37,662.68L559.69,662.48L560.24,662.85L561.31,662.95L561.32,663.79L561.82,664.44L563.24,664.67L563.35,665.99L565.65,665.8L566.26,665.3L566.95,665.73L567.57,665.36L568.06,665.47L568.68,665.92L568.15,666.55L570.53,667.99L570.53,667.99L570.44,668.69L569.73,668.52L569.08,667.92L568.28,668.44L568.05,669.38L568.24,669.64L568.78,669.55L568.55,670.97L567.82,671.69L567.71,672.68L566.51,673.91L566.51,675.75L567.73,675.58L567.6,676.34L567.84,676.58L568.83,676.48L568.96,677.56L568.96,677.56L568.61,677.23L568.18,677.37L567.98,678.52L566.86,681.08L564.12,682.26L563.54,685.21L562.21,685.49L561.47,686.8L561.53,687.84L560.63,690.44L560.91,691.06L562,691.99L561.54,692.96L562.21,694.42L562.91,695.12L564.18,695.6L563.7,697.14L563.69,698.88L563.1,699.45L562.63,700.71L560.96,702.26L560.39,701.86L558.88,702.3L559.02,703.04L556.96,704.42L555.99,704.18L554.71,702.68L553.28,702.33L552.4,702.79L552.4,702.18L552.07,701.93L550.58,702.86L549.62,701.82L548.05,701.51L547.33,701.95L546.33,701.27L545.8,701.59L545.64,702.12L543.92,702.61L541.03,702.21L540.1,701.04L537.62,701.35L536.84,699.84L536.1,699.34L535.68,696.53L535.16,695.29L529.75,695.22L529.38,694.99L526.76,695.38L525.89,694.67L526.25,693.17L526.08,692.93L524.71,692.87L524.22,693.26L524.2,693.78L523.26,693.83L523.25,693.23L522.22,693.02L521.51,691.68L521.15,691.86L520.82,693.7L519.87,694.1L519,694.07L517.8,693.48L517.1,693.65L516.37,694.34L516.3,695.28L514.83,695.61L514.75,696.61L513.51,696.31L512.67,696.61L510.3,696.54L509.79,696.27L509.29,697.97L509.84,698.13L509.97,698.97L509.4,699.35L509.25,699.91L508.39,699.75L507.14,700.12L506.46,701.53L505.12,701.31L504,701.89L502.81,701.73L501.91,701.96L501.67,702.32L501.67,702.32L501.51,700.67L500.84,699.74L499.71,699.51L499.67,699.09L500.21,698.26L501.11,697.73L500.81,696.59L501.21,696.69L501.57,697.56L502.42,697.82L503.04,697.55L503.54,696.59L503.37,696.11L501.34,694.48L501.21,693.62L500.39,692.91L499.95,692.02L499.42,692.06L498.77,691.43L498.68,690.7L497.59,689.83L497.65,688.88L496.87,687.22L497.28,686.01L495.81,684.3L495.81,684.3L496.74,684.19L497.49,683.61L498.76,683.29L498.55,684.32L499,684.51L500.5,683.91L501.79,684.55L502.53,684.08L503.65,682.53L504.64,682.32L504.94,681.97L504.2,680.25L504.39,679.36L505.02,678.74L504.85,677.54L505.1,677.34L505.76,677.68L506.34,677.46L506.6,677L507.74,677.09L507.74,677.09L509.16,678.3L510.19,680.4L511.54,679.82L512.1,679.96L512.53,680.54L514.42,680.25L516.03,680.91L517.04,680.65L517.75,681.59L518.48,681.78L520.67,681.14L521.62,681.36L523.46,680.65L524.76,680.71L528.34,677.31L528.99,676.85L530.28,676.6L530.57,675.1L531.34,674.52L531.36,673.3L532.46,672.23L532.51,671.35L533.09,671.02L534.15,668.63L534.97,668.19L536.53,668L537.27,664.65L537.83,664.23L537.83,663.81L537.24,663.25L537.96,662.62L540.12,662.37L540.19,662.59L541.27,661.72L542.63,662.48L545.07,661.14L545.31,661.51L546.07,661.23L547.49,661.61L547.92,660.99L548.59,660.83L548.77,660.2L550.07,660.82L552.01,660.12z"
},
{
"id":"RU-TV",
"title":"Tver'",
"d":"M120.68,596.87L121.26,596.96L121.88,595.45L122.27,595.42L122.49,594.35L123.85,594.02L123.33,593.08L124.15,592.52L124.85,592.86L125.12,592.46L128.96,597.31L128.96,597.31L129.24,598.14L129.08,598.54L128.7,598.48L128.41,598.9L128,598.77L127.53,599.45L127.99,599.96L127.05,600.9L127.6,601.04L127.88,601.72L128.77,601.75L129.69,603.15L128.87,603.26L128.58,604.15L127.22,604.66L127.15,605.15L128.11,605.06L128.54,605.45L127.52,605.46L127.53,605.91L127.96,605.92L127.4,606.68L128.8,607.18L129.35,607.81L129.78,608.92L130.7,609.64L130.87,611.55L132.15,612.99L132.67,613.15L133.25,612.98L133.46,612.54L134.03,612.53L134.32,613.61L133.79,614.36L133.25,614.26L133.23,615.02L133.45,615.5L133.88,615.64L133.54,616.13L133.98,617.07L133.7,617.46L132.72,617.78L133.33,618.09L132.97,619.04L133.24,619.94L133.58,619.89L133.95,620.45L133.95,620.45L132.3,620.65L131.79,619.3L131.12,619.15L129.79,618.1L128.62,618.71L128.67,619.67L128.14,620.39L127.74,620.2L127.1,620.66L126.04,620.26L125.15,620.78L125.53,621.15L125.59,621.78L125.33,622.18L125.4,623.48L124.68,623.52L123.22,622.86L123.26,623.12L121.33,624.1L121.18,624.45L120.51,624.29L119.1,625.36L118.42,625.23L118.03,626.23L117.74,625.76L116.11,625.36L115.7,625.59L115.59,624.7L115,624.34L114.65,624.79L114.57,624.51L114.17,624.81L113.99,624.6L113.76,625.13L113.23,624.78L113.14,625.75L113.86,625.7L113.5,626.71L113.77,627.36L112.41,627.77L112.74,628.42L112.19,629.18L112.6,629.5L111.25,631.17L111.25,631.17L108.82,630.98L108.27,631.76L107.03,631.31L106.07,630.46L105.59,631.19L104.99,629.88L103.44,630.14L103.08,629.76L102.47,629.84L101.98,630.5L102.53,630.9L102.22,631.88L101.96,631.94L101.93,631.47L101.62,631.22L101.33,631.43L101.18,631.07L100.9,631.62L101.21,632.23L100.7,632.97L100.18,632.9L100.24,633.59L99.58,634.06L98.67,633.98L97.92,634.36L97.44,635.36L97.07,634.81L96.69,635.28L96.27,634.83L95.87,635.52L94.06,635L93.46,635L93.28,635.53L92.95,635.43L93.36,634.65L92.84,634.4L92.57,635.25L92.46,634.88L91.79,634.61L91.44,634.98L90.69,634.73L90.01,635.22L89.56,634.89L90.21,634.55L89.49,634.51L89.3,633.8L88.02,634.03L87.95,634.8L86.6,633.83L85.62,633.88L84.72,633.44L84.72,633.44L84.26,631.9L84.49,631.33L84.28,630.53L85.14,629.97L85.31,629.5L84.84,628.21L85.37,627.7L84.87,627.26L84.91,626.62L85.46,626.53L85.07,626.18L83.84,626.18L83.17,625.7L83.5,625.3L83.24,624.64L81.74,624.28L81.95,622.33L80.68,621.68L80.23,621.05L80.69,620.61L80.13,620.56L80.78,619.92L81.26,618.15L81.53,618.07L81.53,618.07L83.21,618.84L83.66,618.35L86.14,618.75L86.54,617.82L87.03,617.69L86.72,617.33L87.28,616.52L87.67,616.73L87.92,616.3L88.44,616.19L88.73,616.9L89.03,616.78L88.86,616.31L89.22,616.25L89.17,615.81L89.96,615.59L90.17,615.21L90.85,615.35L90.94,614.29L91.84,614.39L91.89,614.02L92.54,614.04L92.96,613.41L93.74,613.44L94.75,611.75L95.1,611.6L95.58,611.9L95.91,611.5L96.45,612L97.35,611.38L98.1,612.28L98.31,611.6L97.75,611.21L97.77,610.7L97.96,610.19L98.56,610.01L98.34,609.44L98.62,608.84L98.33,608.48L99.25,608.15L99.86,608.4L100.35,607.94L100.02,607.25L100.22,606.54L101.03,605.96L101.21,604.78L100.08,603.84L101.26,602.25L102.58,602.46L103.74,601.19L103.81,601.53L104.66,601.4L105.33,602.02L105.94,602.02L106.25,602.49L106.77,602.33L108.27,603.22L108.73,602.74L108.42,602.21L108.46,601.48L109.05,600.88L109.79,601.28L110.12,601.1L110.8,601.64L111.09,601.29L111.83,601.15L112.81,599.93L112.5,599.29L112.78,598.95L114.51,598.08L117.15,598.57L117.33,597.7L117.97,597.96L118.49,597.35L118.87,597.58L119.32,597.1L120.19,597.32z"
},
{
"id":"RU-TYU",
"title":"Tyumen'",
"d":"M332.24,596.26L332.7,595.82L334.61,596.18L338.35,595L338.3,591.88L339.81,590.63L340.46,590.82L340.77,591.45L344.13,589.63L345.08,588.1L347.38,587.75L349.79,586.83L350.72,585.07L351.14,582.66L353.01,582.67L356.81,579.57L355.68,577.7L356.6,576.94L357.92,576.81L358.92,577.28L358.96,578.25L362.09,577.13L363.36,578.13L365.31,578.96L367.45,578.38L368.13,579.14L369.63,578.43L370.94,579.88L373.53,581.68L374.54,582.8L376.01,582.98L378.58,586.1L378.71,587.57L380.12,588.9L381.37,588.16L382.33,588.46L382.49,589.01L381.88,589.85L383.31,591.18L382.35,592.29L383.29,592.73L385.05,593.24L387.5,592.46L388.39,593.26L389.39,593L390.69,594.4L394.33,594.34L396.01,594.71L397,594.49L397.96,595.13L397.96,595.13L398.42,595.71L398.09,596.2L398.09,596.2L396.55,597.65L396.33,598.63L395.04,599.05L393.92,600.36L392.96,600.62L390.85,602.44L383.66,602.16L382.32,603.56L382.59,603.88L381.35,604.53L379.91,604.02L376.66,604.1L375.96,603.11L375.41,602.83L370.43,603.66L370.04,602.77L369.98,601.09L370.34,599.01L369.04,598.55L368.98,597.72L368.08,597.57L367.35,596.89L366.76,599.16L365.02,603.41L364.67,606.72L364.64,607.45L365.29,608.03L366.33,610.46L364.14,612.43L364.11,612.76L364.59,613.5L365.45,613.83L365.82,614.61L366.75,614.56L366.95,613.19L367.27,612.96L368.61,613.04L369.31,615.04L372.18,618.24L372.7,620.13L372.62,620.69L372.2,620.93L372.29,621.33L371.83,621.66L371.42,621.56L370.94,622.3L369.85,622.08L369.47,622.26L368.75,621.84L369.24,623.74L368.04,624.8L367.48,624.64L366.98,625.08L367.15,625.42L367.86,625.54L368.38,626.66L366.74,627.53L367.4,628.1L367.69,629.45L367.15,631.47L366.64,631.97L365.26,631.9L364.98,632.3L365.21,632.73L367,632.53L367.13,632.74L365.28,633.74L365.69,635.33L366.6,635.53L366.63,635.83L366.18,636.95L365.62,637.34L365.11,637.24L364.56,638.24L364.83,639.45L364.83,639.45L364.39,639.44L363.93,640.41L362.65,641.23L362.17,641.22L361.46,640.55L360.67,640.35L360.1,639.26L358.71,638.6L357.42,638.63L356.59,638.31L355.34,638.7L354.54,637.75L353.56,637.48L353.35,638.41L353.79,638.45L353.96,639.22L352.24,638.4L351.46,639.65L351.46,639.65L351.41,638.21L348.25,635.11L347.88,633.66L345.85,634.17L345.1,633.32L343.9,633.72L342.4,633.36L341.39,630.62L339.74,630.59L339.31,629.87L338.53,630.39L337.83,630.28L337.27,629.32L335.84,630.5L334.25,628.82L332.41,629.65L330.13,627.12L329.78,626.2L326.27,625.77L326.05,625.36L326.32,624.78L325.21,622.87L325.37,621.22L325.01,619.96L325.01,619.96L326.73,619.66L327.23,618.19L327.07,617.9L326.11,618.05L325.9,617.68L324.35,610.86L325.32,609.21L324.46,608.19L328.19,606.11L329.11,606.77L329.99,606.12L330.45,605.31L331.21,605.06L331.59,604.41L333.87,603.12L332.68,600.3z"
},
{
"id":"RU-UD",
"title":"Udmurt",
"d":"M227.91,628.39L228.43,627.66L227.71,627.12L228.41,626.3L227.22,625.48L227.04,624.75L225.95,623.69L226.21,623.09L225.99,622.22L226.24,621.53L227.46,621.58L227.8,620.37L228.56,619.72L228.66,619.08L227.77,618.15L225.66,613.41L226.4,611.62L226.98,611.2L228.06,611.07L228.6,611.33L229.24,611.1L229.21,610.55L230.18,609.97L230.29,609.36L231.08,608.56L231.48,607.39L231.21,604.91L231.66,604L230.85,603.59L230.8,602.72L229.65,601.62L230.56,599.27L231.53,598.12L232.74,597.55L233.38,597.53L235.13,598.28L238.06,598.51L238.41,598.15L238.57,597.11L240.01,596.58L240.85,598.21L241.95,598.29L242.03,597.77L242.33,597.66L242.58,597.97L243.15,597.64L243.63,597.83L243.99,597.41L244.75,597.31L244.75,597.31L245.56,599.41L245.05,600.59L245.98,602.51L247.21,604.12L247.74,606.27L247.26,607.46L247.28,608.57L246.81,609.38L248.19,610.63L248.37,611.24L247.78,611.82L247.58,612.72L247.78,613.05L248.54,613L248.83,614.74L248.56,615.26L248.74,615.79L249.35,615.86L249.48,616.18L247.82,617.31L246.83,619.43L245.39,619.61L245.27,620.37L245.59,620.84L245.52,621.8L245.96,622.35L246.08,621.6L246.8,621.21L247.21,621.42L247.03,622.17L248.2,623.64L248.84,623.84L249.25,625.48L249.25,625.48L249.14,626.33L247.8,627.04L247.09,628.55L245.29,629.8L244.91,630.52L244.91,630.52L241.95,631.86L241.05,631.04L241.19,630.62L242.23,629.91L242.25,629.05L243.22,628.39L243.27,626.97L241.63,626.35L241.39,626.72L241.89,628.01L241.51,628.5L240.85,628.36L239.4,627.17L239.19,624.84L239.98,623.38L239.66,622.91L238.61,623.71L238.86,624.23L238.34,625.15L237.32,625.39L236.11,626.5L236.13,626.74L237.73,627.34L238.3,628.02L238.12,628.53L237.29,628.13L237.07,628.37L237.55,629.6L237.03,630.02L236.48,629.2L235.49,629.84L234.64,628.82L233.7,629.3L233.9,630.97L233.52,631.53L233.15,631.6L232.33,630.7L231.84,630.62L231.02,630.88L229.66,630.49L228.59,630.97L227.93,630.48L227.99,630.12L228.7,629.02L229.8,628.15L229.44,627.95z"
},
{
"id":"RU-ULY",
"title":"Ul'yanovsk",
"d":"M198.17,646.34L199,647.31L198.74,647.62L199.05,648.77L199.34,648.17L200.2,648.6L200.49,648.45L200.33,647.72L201.31,646.59L201.22,646.05L201.73,645.87L202.17,646.2L202.25,647.25L202.7,647.52L202.94,646.28L203.67,646.4L204.14,645.64L204.71,646.04L205.35,645.87L205.36,646.61L206.35,646.86L207,647.55L208.47,647.54L209.35,647.23L210.5,645.53L211.45,645.47L210.56,645.04L211.34,644.95L211.64,644.42L211.91,644.24L212.06,644.54L212.46,644.11L213.61,645.09L214.82,647.41L214.67,647.91L216.03,647.89L216.79,648.72L218.25,648.68L218.25,648.68L219.27,650.33L219.19,651.3L219.58,652.14L219.03,652.99L218.93,654.33L217.17,655.81L217.78,656.56L217.45,656.92L216.24,656.43L214.71,657.29L213.65,656.54L212.4,656.8L211.75,656.57L212.11,657.12L210.71,656.95L209.39,658.76L207.02,657.88L206.64,658.3L207.71,658.79L207.82,659.11L207.54,659.32L206.19,658.97L205.75,659.27L205.68,659.64L206.16,660.03L206.32,660.83L206.06,661.57L204.72,661.11L203.72,661.58L203.71,662.07L203.24,662.59L204.01,663.77L204.56,664.03L204.45,664.98L204.89,665.51L204.62,666.54L204.8,666.85L205.48,666.5L205.84,666.69L205.71,667.12L206.71,667.24L207.32,667.95L206.65,669.31L206.1,669.54L206.1,669.54L205.44,669.22L204.61,669.78L203.95,669.64L203.51,670.54L202.93,670.69L202.25,670.16L201.72,670.97L202.1,671.92L201.73,672.21L200.45,671.62L199.23,672.45L197.91,672.26L197.55,671.89L196.74,672.22L196.32,671.43L195.2,671.82L194.75,671.48L194.75,671.48L194.93,670.82L195.93,670L196.06,669.46L195.55,668.15L195.92,665.34L195.5,664.48L195.84,663.53L195.59,662.85L194.27,661.9L194.18,661.43L192.89,661.62L192.52,661.31L192.57,659.77L190.82,657.61L190.62,656.42L190.14,655.83L189.32,655.28L188.23,655.64L187.91,655.49L187.91,655.49L189.05,653.55L191.65,652.78L193.31,651.49L193.96,651.32L193.98,650.34L193.22,650.32L193.05,650.07L193.63,649.16L192.54,649.21L193.12,648.6L192.82,648.18L192.26,648.15L192.97,647.56L192.44,645.83L192.44,645.83L193.95,646.89L194.73,646.85L195.25,647.45L196.11,646.58L196.77,646.51L197.37,647.02z"
},
{
"id":"RU-VGG",
"title":"Volgograd",
"d":"M167.14,687.6L170.3,689.98L171.12,690.29L173.39,688.91L174.03,689.06L175.02,688.4L175.26,688.57L175.02,689.25L175.23,689.5L176.06,689.27L177.05,688.33L178.65,688.19L179.28,688.85L179.79,688.36L181.08,688.39L181.76,689.05L182.61,689.12L184.41,691.72L184.24,693.38L183.46,694.06L183.93,695.53L185.06,695.09L187.25,695.28L187.5,694.9L186.98,693.59L187.64,693.09L188.23,693.15L190.01,694.44L189.91,695.67L190.21,696.02L191.54,695.38L192.54,695.69L193.26,695.08L193.45,694.17L193.83,693.97L195.15,694.55L195.69,695.64L196.74,696.58L197.75,696.34L198.27,697.39L199.28,697.3L199.28,697.3L199.09,697.93L198.33,698.26L198.51,699.02L198.04,699.51L198.6,700.56L198.08,701.64L197.33,702.55L195.58,703.19L195.4,703.51L194.61,709.1L196.32,710.46L196.55,710.94L195.97,712.42L194.58,713.41L193.35,716.48L193.35,716.48L193.16,715.86L191.73,714.87L190.83,714.39L189.47,714.33L188.05,716.08L186.04,717.41L183.73,717.65L183.73,718.03L184.56,718.23L184.62,718.67L183.16,718.4L181.99,720.27L182.38,720.91L183.3,721.2L184.2,722.13L184.2,722.13L183.69,722.38L182.25,721.74L181.6,721.75L181.42,722.11L181.69,722.64L181.23,722.89L180.67,722.93L180.31,722.53L179.26,723.01L179.01,722.72L179.21,721.65L177.88,721.28L177.34,721.93L177.16,722.76L178.58,723.48L178.34,723.99L177.54,724.92L176.86,724.95L175.79,724.41L175.06,724.77L175.07,725.61L172.89,726.91L172.61,727.83L172.73,729.17L172.73,729.17L169.74,729.89L169.08,729.41L169.17,728.53L168.34,728.45L168.1,728.92L167.57,729.01L165.79,726.06L165.57,724.98L163.68,723.52L160.45,723.04L160.42,722.33L160.91,721.66L160.55,720.87L161.34,720.49L160.92,719.04L162.35,718.02L165.07,717.2L165.36,716.83L165.21,716L166.09,714.31L165.09,712.71L164.49,712.37L163.4,712.34L163.6,711.67L163.01,710.98L161.01,710.99L160.95,710.02L161.26,709.51L160.92,708.34L161.89,705.5L161.77,704.63L159.7,702.81L159.12,702.93L157.94,702.42L158.16,701.42L157.06,700.86L156.87,699.95L156.31,699.65L156.31,699.65L157.18,698.11L157.02,695.95L157.66,695.62L156.14,693.8L155.17,693.25L155.38,692.93L156.69,692.63L156.79,691.91L157.34,691.39L157.89,691.46L159.02,690.74L159.29,689.81L160.16,688.74L163.15,689.02L163.9,688.66L165.27,688.63L165.72,687.96z"
},
{
"id":"RU-VLA",
"title":"Vladimir",
"d":"M141.95,620.43L142.35,620.5L143.36,619.82L145.15,620.38L145.21,621.24L144.7,622.38L145.34,622.44L146.02,624.29L146.93,624.48L147.58,625.01L148.23,623.7L148.58,623.8L148.72,623.43L149.42,623.38L149.59,623.01L151.16,622.59L151.82,622.8L152.07,623.78L153.38,624.11L153.85,624.56L154.04,624.15L154.77,623.85L155.01,624.2L156.51,624.29L156.96,624.92L157.51,624.47L159.6,623.86L159.84,625.52L160.74,625.9L161.62,625.14L161.66,624.58L162.33,624.39L163.37,624.62L163.54,625.14L164.76,625.06L164.76,625.06L165.44,625.72L165.65,627.14L167.01,627.69L166.96,628.22L166.3,628.97L165.46,629.16L165.1,629.6L165.36,629.92L165.27,630.56L164.5,631.29L163.7,631.42L163.36,632.91L162.2,633.54L160.95,635.25L160.91,636.65L161.29,637.77L160.52,638.71L160.17,638.71L159.86,640.38L159.42,641.25L158.91,641.45L158.91,641.45L158.26,641.35L158.02,641.61L157.62,641.09L156.39,641.53L155.07,640.32L154.63,640.26L154.06,640.82L154.07,641.43L153.73,641.37L153.12,639.88L152.44,639.8L152.27,640.56L151.6,640.26L151.39,640.63L150.31,640.67L149.9,639.89L150.01,639.15L149.59,639.02L149.12,639.66L148.54,639.68L148.33,639.28L148.81,639.12L148.67,638.82L147.74,638.98L147.74,638.98L147.18,637.87L147.56,636.88L147.33,636.51L146.54,636.53L146.8,634.83L145.59,633.84L145.43,632.61L144.34,632.5L143.74,633.1L142.81,633.16L142.53,633.71L142.41,633.32L141.41,633.35L141.17,632.57L141.43,632.2L140.92,632.48L139.85,632.35L139.33,631.61L139.52,631.25L139.18,631.33L139.37,631.13L137.83,631.37L137.08,630.65L136.16,630.64L136.03,630.42L136.33,630.23L135.85,629.57L135.5,628.14L135.68,627.73L135.32,627.8L134.79,627.03L135.13,625.4L134.79,625.32L134.79,624.56L134.39,624.58L134.12,624.07L134.37,623.83L133.93,623.62L134.56,623.04L134.15,621.51L134.74,621.37L134.74,621.37L135.52,622.1L135.62,623.06L136.09,623.21L137.24,622.44L137.82,622.53L138.41,623.19L139.44,623.18L139.81,622.71L140.79,623.44L141.3,623.26L141.19,622.84L141.67,622.12L141.43,622.09L141.36,621.38z"
},
{
"id":"RU-YAN",
"title":"Yamal-Nenets",
"d":"M341.72,428.62l0.59,0.44l0.15,0.75l-0.5,-0.02l-0.93,-1.01l-0.38,0.09l0.35,-0.29L341.72,428.62zM421.52,351.59l0.27,0.32l-0.43,0.48l0.04,0.52l-0.41,0l-0.54,-0.76l0.34,-0.56L421.52,351.59zM420.9,349.6l-0.94,0.43l-0.82,1.27l-0.71,0.15l-0.56,0.76l-0.24,-0.05l-0.6,1.58l-0.93,-0.22l-0.44,0.01l0.06,0.24l-2.69,-0.12l-2.12,0.47l-0.67,-0.54l0.63,-1.57l1.87,-1.51l0.99,-2.43l1.96,-1.87l3.95,1.04l0.86,1.08L420.9,349.6zM342.3,390.25l0.08,-0.98l-0.27,-0.15l-0.12,-1.42l-0.43,-0.85l-0.92,-0.15l-0.95,0.51l-0.39,0.57l-1.32,0.25l-0.52,0.41l0.2,-1.31l-0.61,-1.1l0.83,-0.82l1.05,-2.31l-0.23,-0.67l0.44,0.13l-0.31,-0.21l0.17,-0.43l0.54,-0.06l-1.62,-1.01l1.37,-3.48l3.01,-1.85l1.01,-0.79l0.61,-1.03l2.5,-1.78l2.22,-2.99l0.85,-1.9l0.91,-2.41l0.97,-5.98l0.61,-0.39l-0.45,-0.4l0.63,-4.02l0.45,-0.14l-0.38,-0.12l0.34,-3.32l0.6,-2.17l0.21,-2.34l0.6,-0.01l-0.02,-0.31l-0.46,0.07l-0.04,-0.37l1.62,-2.54l1.27,-4.22l1.71,-0.35l1.23,0.22l0.11,0.69l-0.31,-0.11l-1.37,0.74l0.02,0.69l0.45,0.21l1.87,-0.37l0.09,-0.3l1.27,0.31l1.08,-0.36l1.74,0.11l0.46,-0.29l1.72,0.54l2.18,-0.52l1.84,0.28l1.79,-0.26l2.08,1.26l0.96,0.22l-0.04,0.46l-0.39,0.21l0.45,0.18l0.22,-0.21l0.14,0.31l0.18,-0.6l-0.36,-0.21l0.5,-0.04l5.39,3.1l-1.08,-0.01l0.26,0.92l0.55,0.6l-0.8,0.89l0.13,1.28l0.56,1.06l-0.46,0.25l-0.8,-0.21l0.9,0.37l0.39,-0.16l-0.19,0.81l0.51,4.36l-0.99,1.83l0.12,1.54l-0.94,1.47l-0.47,3.71l-0.89,0.91l-0.22,-0.09l-0.1,3.55l-0.89,1.06l-0.32,1.74l-0.75,0.27l-0.54,0.75l-0.43,0.03l-0.68,1.3l0.25,1.41l0.99,1.61l0.25,1.32l1.35,1.76l1.94,1.11l-0.07,0.23l0.63,0.02l0.33,0.55l0.21,1.06l-0.45,1.7l1.73,3.01l-0.32,3.84l-0.58,2.31l0.45,1.53l-0.06,2.52l-0.88,0.34l-1.21,1.52l-0.36,1.14l1.14,2.15l-0.64,3.17l0.87,1.8l0.52,2.23l0.01,0.83l-1.18,2.65l1.27,3.42l-0.5,1.08l-0.82,-0.4l0.95,2.98l-0.94,1.61l-0.17,2.27l0.69,3.36l0.49,1.02l1.14,1.5l2.3,1.8l2.47,2.54l0.93,2.34l-0.19,1.04l-0.02,-1.3l-0.6,0.17l-0.46,1.87l-2.38,2.98l0.16,1.1l-0.52,1.48l1.24,3.37l-0.16,1.33l-0.78,0.71l0.33,1.77l-0.22,0.4l0.01,-0.67l-1.61,0.65l0.08,1.02l-2.05,0.93l-0.29,1.51l-0.99,0.9l0.27,1.32l-0.44,1.34l-1,0.19l-0.35,-0.37l-0.49,0.56l0.59,1.13v1.75l-0.19,0.07l-0.06,-0.48l-0.65,0.02l-1.29,0.71l0.48,-0.05l0.39,0.4l-0.22,0.5l0.34,0.48l-0.57,0.17l-1.17,1.46l-0.19,0.77l0.28,0.42l-0.74,-0.22l0.12,0.38l-0.39,0.14l0.11,-1.11l-0.85,-0.16l-0.38,0.62l-0.94,-1.18l-0.52,0.52l1.06,0.8l-0.58,-0.11l-0.54,0.53l-0.87,0.09l-1,1.11l-1.37,-0.16l-0.59,0.85l-2.02,0.72l-1.4,-0.58l-0.4,0.44l-1.01,0.03l-1.21,-2.21l-0.31,0.09l-0.04,0.77l-1.49,0.05l-1.36,-0.69l-1.23,-0.15l-0.82,-0.51l-0.1,-0.46l-0.47,0.12l-0.09,-0.25l-0.81,0.83l-0.81,0.01l-0.43,-0.61l-0.44,0.56l2.31,0.27l-0.21,0.77l-1.01,0.48l0.02,0.31l1.54,0.02l0.23,0.27l-0.33,2.5l0.51,0.75l1.73,1.55l2.74,0.65l0.88,1.14l3.17,1.22l4.43,-0.54l2.95,0.26l2.18,0.77l0.65,1.02l1.21,-0.19l0.23,0.46l1.71,-0.51l0.09,-0.62l0.45,-0.05l0.74,-1.06l-0.44,-2.02l-0.35,-0.41l0.5,0.25l0.07,-0.28l-0.57,-0.2l0.8,-0.7l0.46,-1.03l0.33,0.25l0.15,-0.42l0.09,0.21l0.1,-0.27l1.87,-0.26l0.53,-0.38l0.84,-1.51l3.32,-1.82l0.89,-1.04l0.05,-0.88l1.69,-1.09l0.68,-3.66l-0.24,-1.89l1.57,-2.91l4.12,-4.2l0.37,-1.41l0.14,-5.43l-1.08,-3.54l-2.4,-3.06l1.07,-2.46l-0.16,-3.26l0.33,-0.99l0.9,-1.03l1.07,-0.66l4.1,-1.86l2.21,-0.32l3.21,-1.61l2.81,-0.28l0.54,0.31l0.61,2.02l0.08,0.95l-0.43,1.22l0.16,0.47l2.73,2.65l0.35,1.28l0.34,-0.02l-0.01,-0.44l0.42,0.13l1.19,1.58l-0.13,0.38l-0.63,-0.02l0.31,1.86l-0.93,1.65l0.33,0.69l0.66,-0.03l0.39,0.32l-0.92,2.56l0.02,3.17l0.61,1.11l-0.54,1.42l-0.74,-0.18l-0.36,0.63l0.75,1.07l1.56,1.14l1.15,0.45l1.11,1.28l-0.56,4.68l0.24,0.09l0.15,-1.53l0.43,-0.62l1.41,1.41l-0.4,-2.1l0.89,-0.72l1.66,-0.86l0.85,0.71l1.28,-0.19l-0.38,-0.25l0.32,-0.1l1.58,1.05l0.77,1.52l0.75,0.72l1.01,0.4l0.98,1.36l0.54,0.21l0.67,-0.19l-0.04,0.66l2.33,1.89l0.78,-0.22l1.34,0.63l-0.94,-0.66l0.5,-0.18l0.54,0.23l-0.4,-0.32l-1.7,0.26l-0.75,-0.38l-1.5,-1.22l-0.02,-0.72l-1.21,-0.07l-1.05,-1.5l-1.33,-0.62l-1.11,-2l0.23,-1.09l1.83,0.63l1.57,1.22l0.84,1.75l0.98,0.29l0.13,1.39l0,-1.56l-0.98,-0.29l-1.52,-2.5l-1.62,-1.41l-0.96,-0.35l0.21,-0.47l-0.96,-0.03l-0.33,0.71l-0.68,0.2l-0.73,-0.41l1,-0.12l0.1,-0.53l-0.31,-0.33l-0.82,0.28l-0.37,-0.61l-0.19,0.91l-0.42,-0.5l-1.69,0.41l-0.74,-0.81l-1.02,0.24l0.83,-0.66l-1.09,-0.29l-0.33,-0.85l-0.29,0.65l-0.57,0.29l-1.34,-0.76l-0.07,-2.09l0.39,-0.96l0.6,-0.16l-0.26,-0.37l-0.19,0.21l-0.26,-0.8l-0.06,-2.79l0.8,-1.36l0.92,-0.72l1.97,-0.02l1.14,-0.73l-0.82,-1.93l-0.51,-0.3l-0.77,-1.56l0.56,-0.24l-0.02,-0.48l-1.04,-0.47l-0.14,-0.34l-0.35,-1.32l0.23,-2.28l-0.6,-1.69l-0.11,-1.62l-0.32,-0.43l-1.93,-0.65l-0.86,-0.83l-1.95,-0.82l-0.71,-0.58l-1.25,-1.91l-1.62,-0.07l-2.39,-1.79l-1.07,-0.42l-3.55,-0.03l-1.98,1.84l-0.21,0.97l-2.66,0.37l-2.06,-1.02l-1.82,0.18l-1.83,1.19l-0.85,-0.37l-0.72,-2.1l0.76,-2.32l0.19,-2.15l-0.55,-1.93l-1.62,-2.36l-0.45,-2.68l0.83,-1.08l0.69,-2.71l-0.19,-0.45l0.48,-1.92l-0.2,-0.59l-0.55,-0.37l3.66,-6.26l0.57,-1.75l0.2,-2.39l-0.6,-1.92l-2.31,-3.61l0.15,-2.08l-1.35,-1.77l-1.07,-3.65l-1.98,-2.87l-1.77,-1.12l-0.56,-0.7l0.61,-1.35l2.41,-2.73l0.6,-1.34l0.4,-1.55l-0.49,-1.3l0.34,-0.72l1.81,-1.49l5.36,-2.94l2.27,-2.48l1.07,-1.8l0.57,-2.71l-0.06,-3.53l-0.71,-4.8l-0.61,-2.21l-0.82,-1.58l1.07,-1.65l0.5,-0.14l3.36,3.01l0.13,0.35l-0.53,0.4l-0.12,-0.54l-0.45,0.16l-0.2,0.83l2.48,4.07l-0.73,-0.08l-0.41,1.01l0.47,2.6l0.99,2.69l-0.26,0.58l-0.78,0.47l-0.48,1.38l-0.12,1.75l-0.58,1.54l0.38,0.75l-0.36,1.11l-0.66,0.12l0,-0.49l-0.25,0.65l0.18,1l-0.4,2.45l0.34,1.25l1.39,1.73l-0.38,1.47l0.63,1.29l-0.7,0.99l-0.06,1.03l-0.59,-0.24l-0.73,0.66l0.56,1.81l0.8,1l1.35,0.42l2.25,1.61l1.47,0.4l0.68,-0.19l0.87,0.42l2.37,-0.05l4.29,0.78l1.25,-0.24l2.57,0.8l0.88,1.7l0.16,1.68l2.9,1.05l0.25,0.46l0.24,-0.11l0.29,-2.31l-1.15,-1.08l-0.38,-1.22l0.41,-3.01l-1.87,-0.5l-0.62,0.7l-0.24,-0.74l0.46,-1.54l-0.56,-0.14l-0.31,0.15l0.38,0.44l-1.31,0.43l0,0.78l-0.83,-0.38l-0.45,-0.66l-0.31,-0.11l-0.13,0.24l0.47,0.33l-1.18,-0.42l-1.27,-1.13l-0.38,-1.3l-0.16,0.23l-0.19,-0.47l-0.6,0.3l-2.29,-1.19l-0.75,-1.13l-1.84,-1.15l-0.26,-0.66l0.08,-1.52l-0.97,-1.83l-0.65,-2.96l-0.61,-0.26l0.45,-0.55l0.75,-0.23l2.24,-2.57l2.96,-0.77l0.49,0.17l-0.13,0.5l0.44,0.62l1.3,0.91l1.29,1.28l1.05,1.61l0.69,0.42l1.63,0.11l2.01,-1.14l0.96,-1.91l-0.18,-1.29l-1.27,-2.07l-0.52,-0.33l-1.66,0.12l-1.52,0.99l-0.82,-0.23l-0.11,-0.92l0.83,-1.74l-0.41,-0.69l0.57,-0.07l0.71,0.64l0.38,-0.07l1.33,-2.74l1.38,-0.69l0.11,-0.45l0.76,0.37l0.25,-0.28l0.42,0.08l0.2,0.46l1.85,0.95l0.15,0.55l0.06,-0.69l-0.69,-0.14l-0.57,-0.81l0.84,-0.95l0,0l1.36,2.52l-0.12,1.33l2.16,2.24l2.09,1.57l1.63,0.25l2.16,-0.37l0.71,0.88l1.4,0.45l2.28,1.66l0.45,1.18l-0.2,0.53l-1.56,0.52l-0.59,3.01l-0.96,1.44l-1.36,0.66l-2.86,0.08l0.14,2.2l-0.23,0.76l-0.59,0.26l-0.17,0.84l0.51,2.33l0.64,0.57l0.84,0.07l2.47,3.4l2.49,1.21l2.44,0.75l0.55,1.04l0.21,2.8l0.77,1.65l-0.62,2.19l1.25,1.4l-1.19,3.29l1.09,1.25l0.12,0.42l-0.33,0.57l-0.82,-0.08l-1.18,-0.93l-1.56,-0.03l-0.86,0.43l-0.05,0.71l-3.55,3.53l-1.08,2.11l-0.12,-0.59l-0.56,-0.22l-0.5,-0.12l-0.32,0.49l-0.07,1.44l-1.41,2.3l-1.53,1.51l0.26,1.18l0.84,1.6l-0.25,1.75l2.84,0.62l1.35,4.51l0.55,0.12l0.78,1.37l0.85,0.47l2.2,-0.19l1.87,0.78l0.94,-0.11l2.34,1.8l0.88,0.08l1.69,-1.04l0.96,0.26l0.73,-0.17l0.61,-0.64l0.23,-0.95l-0.15,-1.25l0.51,-0.86l2.04,1.5l0,1.1l-1.08,1.51l0.14,0.74l2.34,0.87l1.43,0.14l0.5,0.96l-0.79,0.99l0.98,1.88l0.51,2.69l1.73,1.75l0.33,0.99l0.12,1.1l-1.6,1.08l0.43,2.61l0,0l-0.15,3.04l0,0l-1.19,0.85l-0.23,1.64l-1.01,1.23l-0.1,2.73l-1.2,0.4l-0.98,-0.44l-1.29,0.52l-0.71,-0.03l-0.3,0.34l1.21,2.54l1.01,0.75l0.3,1.92l1.99,2.03l0.05,0.69l-0.58,1.2l0.17,2.06l-1.35,1.61l6.36,5.85l0.13,1.04l1.15,0.74l0.81,2.4l-0.27,0.88l-0.69,0.55l-0.79,1.3l0.07,0.81l1.85,2.23l1.64,3.33l-0.99,0.7l-0.02,0.88l-0.67,0.7l0.24,0.83l0.97,1.26l0.24,1.9l0.44,0.59l0.88,0.27l1.46,-0.35l2.52,1.74l0.34,0.81l-1.28,0.76l1.68,0.56l0.96,0.85l0.76,3.72l-1.71,1.61l-0.54,1.19l0.79,1.88l-0.48,1.04l0.29,0.43l2.09,0.21l2.59,-0.49l0.18,0.54l-0.6,0.71l1.03,0.36l0.68,0.8l0.7,0.12l1.5,-1.08l0.91,0.38l0.2,0.41l0.68,0.07l0.77,3.58l-0.74,1.33l0.69,1.48l-0.18,0.62l0.54,1.64l-0.03,3.52l-1.97,1.45l-1.32,1.44l-1.05,0.59l-0.3,2.76l-1.38,1.43l0.21,0.75l1.4,0.79l0.79,1.82l0.68,-0.12l0.43,0.26l-0.33,1.79l0.16,0.72l-0.38,0.53l0.59,1.5l-0.18,0.79l-0.4,0.32l-0.19,1.3l-1.12,0.96l-0.53,1.33l-1.69,1.69l-0.59,1.4l-0.3,2.05l-2.38,2.8l-0.51,1.34l0,0l-1.35,-1.38l-0.13,-1.02l-0.63,-0.71l-0.79,0.08l-1.33,-2.19l-0.87,-0.36l-1.29,0.98l-0.1,-0.82l-1.1,1.13l-1.65,-0.49l-0.87,-0.68l-0.19,-1.13l-2,-0.63l-0.04,-1.73l-2.81,0.08l-1.95,-1.1l-0.63,0.12l-0.4,0.55l-0.38,1.31l-0.57,0.16l-0.68,-0.4l-1,-1.5l-0.74,0.31l-1.19,-0.77l-0.34,-0.45l0.25,-0.84l-1.94,-2.03l-0.56,-1.38l-0.26,-0.06l-2.16,0.84l-0.33,1.52l-0.75,0.09l0.03,0.3l-1.98,1.86l-1.91,0.49l-0.89,3.51l-4.84,0.22l-2.6,-0.53l-3.8,0.62l-1.58,0.73l-1.52,-0.71l-3.22,-2.51l-1.69,-1.81l-0.79,-1.96l-0.55,-0.54l-1.61,-0.55l-1.17,0.05l-1.23,1.01l-0.49,0l-0.68,-0.93l-3.17,-1.45l-3.68,0.47l-1.75,0.66l-3.67,0.27l-1.61,-1.8l-0.97,-0.5l-4.6,-0.01l-0.76,-0.44l-0.96,-1.62l-0.54,-0.29l-0.45,-1.36l-1.17,-0.1l-0.4,0.11l-1.33,1.91l-1.28,0.25l-2.51,-0.32l-0.94,0.83l-2.94,0.74l-0.81,-3.41l-0.07,-2.53l-0.88,-1.55l-0.54,-0.38l-3.04,-0.09l-0.33,-1.81l-1.71,-3.25l0.61,-0.39l0.55,-0.98l-0.09,-0.92l-0.33,-0.62l-1.8,-1l-1.2,-1.48l-3.29,0.51l-0.34,-0.95l-2.6,0.11l-0.91,-1.01l-1.58,-0.19l-1.21,0.39l0.68,1.39l-0.64,1.01l-0.07,1.44l-3.12,-1.69l-2.64,2.41l-2.42,1.59l-0.5,-0.93l-3.27,0.46l-0.38,-1.19l-1.82,-0.49l-0.69,-0.72l-0.28,-0.88l0.84,-2.6l-0.44,-1.15l-0.51,-0.42l-3.03,0.95l-1.6,-1.28l-4.45,0.53l-2.23,0.86l-2.45,0.32l-1.57,0.78l-0.76,-0.18l-0.67,0.56l-2.78,-0.02l-1.71,1.38l-1.29,0.29l-1.26,-1.11l-0.53,-2l-2.63,-1.2l-1.3,0.67l-2.11,-1.39l-0.22,-0.86l1.59,-1.11l0.65,-1.63l-0.95,-2.25l0.54,-1.29l0.4,-5.25l-1.31,-0.57l-1.68,-1.35l-0.16,-1.46l-0.97,-2.01l-1.71,-1.71l0,0l5.11,-2.69l0.1,-0.95l0.76,-0.96l-0.44,-1.01l0.55,-0.32l0.2,-0.79l0.54,-0.46l0.34,-1.32l1.14,-1.11l0.72,0.34l-0.6,-1.68l0.51,-0.58l0.59,-1.78l1.55,-0.43l1.43,-1.03l1.54,-1.92l1.88,0.01l0.58,-0.85l1.41,-0.7l0.28,-1.13l1.13,-0.54l0.88,-0.03l1.69,-1.44l-0.46,-3.09l0.94,-0.5l0.96,-1.73l1.91,-1.4l1.19,-1.78l2.12,-0.88l0.65,-0.8l0.11,-0.82l-0.63,-1.21l-1.72,-0.64l0.64,-1.11l0.48,-0.25l1.59,0.41l0.45,-0.46l-0.45,-1.47l-1.28,-1.12l0.63,-0.87l0.11,-0.83l-0.42,-0.95l-1.35,0.08l-1,0.61l-1.2,0.09l-1.39,-1.3l-0.34,-5.97l1.09,-1.53l0.01,-0.88l0,0l1.35,-1.36l0.26,-1.02l-1,-2.35l0.33,-1.06l-1.25,-0.7l0.01,-0.89l-0.97,-0.61l-1.37,0.17l-1.68,-1.61l-0.55,-0.27l-0.26,0.72l-0.89,-0.74l0.27,-0.56l-0.6,-1.55l1.13,-0.79l0.27,-0.56l-0.19,-1.71l0.45,-1.15l0.81,-0.8l0,0l1.36,0.15l1.08,1.22l1.38,0.71l5.2,1.62l1.49,1.44l1.11,1.85l-1.1,-1.58l-1.75,-1.52l-1.35,0.03l-0.21,-0.51l-0.51,-0.06l-0.19,0.3l-0.41,-0.41l-0.18,0.2l0.08,-0.45H330l-0.68,-0.46l1.71,1.68l0.68,-0.17l0.71,0.37l-0.24,0.04l0.91,0.17l1.02,0.96l0.45,-0.18l0.1,0.67l0.53,0.49l1.91,1.02l3.67,1.25l-0.7,0.5l0.13,0.79l0.37,0.09l0.67,1.34l1.15,0.42l-0.35,0.19l0.59,0.03l1.95,2.06l0.21,0.66l0.75,0.52l0.1,0.18l-0.87,-0.34l0.56,0.76l-0.02,0.44l0.13,-0.32l0.54,-0.06l1.77,0.99l0.64,0.69l0.34,0.93l-0.36,0.64l-0.34,0.03l0.1,1.21l0.49,-0.01l0.31,0.54l-0.34,0.98l0.23,-0.05l-0.07,-0.46l1.67,-1.64l0.68,-0.08l-0.51,-0.32l0.59,-0.7l-0.23,-0.14l0.1,-0.94l2.31,-4.81l0.83,-3.37l0.67,-0.64l-0.13,-0.98l-1,-0.43l0.55,-0.25l0.16,-0.8l-0.48,-0.07l-0.9,0.63l-0.87,0.06l-1.01,-0.46l-1.21,-1.27l-0.41,-1.37l-1.98,-3.31l-0.64,-2.25l0.68,-0.82l0.26,-2.97l-0.83,0.07l-0.11,0.44l0.3,0.24l-0.61,0.25l-1.24,-0.7l-1.08,-1.46l-0.93,-0.46l-0.04,-0.28l-0.95,0.21l-2.48,-1.87l-0.47,0.4l0.33,0.77l-0.89,0.45l0.46,-0.84l-0.64,0.78l0.09,0.82l0.51,1.04l0.29,-0.02l-0.11,0.24l-0.38,0.18l-0.72,-1.34l-0.03,-5.64l0.92,-3.72l0.21,-0.19l0.34,0.43l-0.54,0.33l0.08,0.71l1.06,0.39l1.27,-0.43l1.02,-1.25l-0.5,-1.7l-0.48,-0.39l-0.34,-1.86l-0.89,-0.01l0.7,-3.4l0.98,-1.6l-1.1,-1.75l0.37,-1.67L342.3,390.25zM394.63,334.31l1.52,1.33l-1.03,-0.91l-0.34,0.18l-0.67,3.33l0.48,1.5l-0.53,0.66l-0.46,-0.18l0.27,-0.52l-0.57,0.25l-0.87,-0.63l-0.2,-0.7l-0.27,-0.05l-0.04,0.31l-0.26,-0.2l-1.36,-1.78l0.77,-2.24l0.87,-0.75l0.8,-0.13L394.63,334.31zM370.41,329.25l0.48,-0.24l0.42,-0.84l1.43,2.99l0.11,1.33l-2.01,0.05l-1,1.02l-0.98,0.42l-1.35,-0.23l-2.22,1.3l-1.18,1.12l-1.74,-0.1l-0.27,-0.3l0.06,-0.61l-0.51,-0.5l0.07,0.48l-0.57,0.19l0.69,1.12l-1.22,-0.12l-0.09,-1.56l0.78,-5.39l-0.23,-2.59l2.93,-1.73l2.72,-0.72l0.88,0.04l2.64,1.64l-0.14,0.31l0.78,0.9l0.15,1.03L370.41,329.25z"
},
{
"id":"RU-VLG",
"title":"Vologda",
"d":"M114.94,558.67L120.62,555.48L122.22,552.94L123.63,553.47L124.12,552.61L124.99,552.23L125.82,552.83L126.24,552.8L126.66,553.51L127.29,553.83L130.12,553.44L130.12,553.44L129.97,555.2L131.6,558.09L131.44,558.73L131.88,559.21L132.7,559.39L133.09,560.32L132.69,562L133.74,562.57L134.36,561.69L134.6,562.17L134.46,563.63L135.75,564.06L136.5,565.43L137.66,565.35L138.43,565.92L140.01,566.25L140.4,565.61L142.42,565.91L143.27,564.96L144.22,564.99L144.93,565.88L145.9,566.21L147.13,565.58L148.23,565.76L148.71,564.69L149.12,564.62L150.37,565.21L151.2,564.81L153.08,566.31L154.47,566.4L155.63,565.72L156.25,564.85L155.92,563.84L157.43,562.76L157.7,563.43L158.64,563.91L159.05,562.7L160.48,563.84L161.01,563.24L161.43,564.06L163.14,565.03L163.86,564.39L164.28,564.41L164.76,563.55L165.43,563.37L166.41,564.05L167.53,565.51L168.45,564.19L169.9,564.82L170.87,564.55L171,563.79L171.9,562.74L172.69,562.52L172.82,561.68L174.73,560.9L175.72,560.95L175.95,561.33L175.77,561.6L176.32,562.27L183.29,562.98L183.86,558.64L187.6,559.15L187.11,561.09L189.05,562.19L191.25,562.04L192.28,561.1L193.37,562.13L194.32,562.03L194.7,562.26L194.31,563.16L194.83,563.62L196.68,563.69L196.68,563.69L196.18,565.17L196.66,567.61L195.37,568.97L194.74,572.22L194.38,572.53L193.72,572.36L191.36,572.75L191.99,574.48L194.22,575.59L195.05,575.37L196.47,573.96L196.19,576.68L195.35,579.1L196.94,579.75L197.16,580.27L197.05,581.75L197.05,581.75L194.73,581.66L194.32,582.17L193.72,582.29L193.58,581.86L192.07,581.98L191.74,583.32L192.05,583.74L191.81,585.11L190.26,585.29L189.98,585.78L189.41,585.68L188.54,587.7L187.38,587.6L186.87,587.17L186.68,587.57L184.17,587.18L183.84,587.69L182.3,587.65L181.81,588.61L178.3,588.06L176.92,588.39L176.88,587.98L176.04,587.78L175.88,587.17L174.75,587.54L173.94,587.12L173.24,587.19L173.22,586.38L171.9,587.03L172,587.44L171.44,587.73L171.18,586.04L170.04,586.52L170.08,587.25L169.78,587.37L169.54,586.99L169.34,587.16L168.65,586.55L168.03,587.01L168.06,587.34L167.03,587.64L166.73,587.38L166.7,588.11L166.32,588.24L165.61,586.98L165.26,586.97L164.75,585.73L163.06,586.1L162.62,586.59L162.07,585.89L161.86,584.61L160.85,584.34L160.12,586.33L161.11,587L160.99,588.75L160.59,588.87L160.36,588.61L160.02,589.21L159.03,589.05L157.87,589.42L156.26,590.49L155.87,591.1L155.58,590.3L155.23,590.51L155.24,590.89L154.67,591.44L155.15,591.78L155.17,592.54L154.87,592.37L154.43,593.24L155.2,594.15L154.65,595.2L154.12,595.3L153.41,596.02L153.59,596.62L153.32,596.47L152.97,596.81L152.97,596.81L152,596.99L152,596.53L151.63,596.38L150.35,596.39L150.02,596.65L149.7,596.36L149.29,596.89L148.54,596.45L148.29,596.8L146.83,595.95L146.61,595.47L147.04,595.36L146.96,594.94L145.13,593.49L144.83,592.64L144.02,592.84L143.54,591.81L142.59,592.05L139.91,590.91L139.52,591.32L138.93,590.83L138.56,591.28L138.9,592.51L138.48,593.28L138.61,593.69L138.22,594.02L137.61,593.69L136.7,593.87L136.74,593.59L136.41,593.5L135.84,593.53L135.8,594.04L134.97,594.3L131.97,593.95L131.65,594.4L131.41,594.1L131.44,594.62L131.9,595.1L131.32,595.26L131.52,595.5L131.27,596.05L130.9,595.8L130.99,595.54L129.81,595.22L129.52,597.29L129.22,597.02L128.96,597.31L128.96,597.31L125.12,592.46L124.85,592.86L124.15,592.52L123.33,593.08L123.85,594.02L122.49,594.35L122.27,595.42L121.88,595.45L121.26,596.96L120.68,596.87L120.68,596.87L119.73,596.75L119.36,596.41L119.3,595.81L118.82,595.46L118.75,594.78L118.26,594.17L116.09,593.33L115.58,592.65L115.19,592.86L113.92,592.12L113.3,592.11L112.35,593.47L112.21,592.44L111.56,592.84L111.83,590.87L110.04,590.33L109.73,590.06L110.15,589.73L108.69,589.01L108.69,589.01L108.48,588.56L108.75,588.44L108.72,587.86L109.8,586.5L110.39,587.17L110.73,586.59L111.34,586.78L112.06,586.04L112.86,586.05L113.09,585.02L113.71,584.15L113.12,583.47L114.13,582.23L114.09,580.87L114.92,581.48L114.79,580.23L113.42,579.94L113.23,579.48L113.3,576.97L113.79,576.37L111.37,575.46L111.78,575.05L111.8,574.48L111.15,573.95L111.29,572.31L111.84,571.54L112.58,567.96L112.25,566.15L111.58,564.62L112.4,563.57L112.84,563.42L113.66,563.82L114.11,563.28L114.42,562.49L113.88,562.06L113.85,561.56L114.83,560.75L115.21,559.69z"
},
{
"id":"RU-VOR",
"title":"Voronezh",
"d":"M134.07,679.47L135.61,678.52L136.44,678.77L136.87,677.82L137.49,678.12L137.86,677.83L138.42,678.03L138.85,678.86L139.55,679.29L140.01,679.09L140.18,678.04L142.23,678.13L142.89,678.46L143.06,679.56L144.48,680.09L145.58,680.08L146.02,679.53L150.32,679.74L150.32,679.74L153.13,680.54L153.39,681.02L153.2,682.21L153.67,682.56L155.49,682.38L156.1,681.66L157.96,681.98L158.99,682.63L159.67,682.4L160.36,683.19L161.21,683.2L161.74,683.56L161.96,682.77L162.65,682.82L163.21,683.95L163.79,683.59L164.47,683.93L164.47,683.93L164.98,684.55L166.36,684.98L166.69,685.4L167.04,686.03L167.14,687.6L167.14,687.6L165.72,687.96L165.27,688.63L163.9,688.66L163.15,689.02L160.16,688.74L159.29,689.81L159.02,690.74L157.89,691.46L157.34,691.39L156.79,691.91L156.69,692.63L155.38,692.93L155.17,693.25L156.14,693.8L157.66,695.62L157.02,695.95L157.18,698.11L156.31,699.65L156.31,699.65L156.03,701L154.07,702.81L153.01,705.27L151.09,705.81L150.2,706.37L148,705.89L147.46,706.57L147.46,706.57L146.92,705.94L145.66,706.18L145.35,706.59L144.5,706.49L143.46,705.79L143.19,704.59L142.05,704.33L141.44,704.61L140.71,704.29L140.44,703.7L140.44,703.7L140.89,703.39L141.49,701.8L141.42,701.22L140.58,700.44L140.14,698.51L140.37,697.96L139.79,696.96L140.32,696.27L140.03,695.58L140.7,695.61L140.82,695.25L139.73,694.84L139.27,694.14L138.74,694.17L138.16,693.42L138.27,692.9L137.52,692.49L137.72,691.55L138.45,691.8L138.7,691.49L138.17,690.93L138.34,690.12L137.68,689.53L136.74,690.35L135.16,689.82L135.07,689.03L135.71,688.64L135.75,688.08L135.55,687.65L134.28,687.3L134.28,687.3L134.54,686.42L134.26,685.03L133.15,683.01L134.98,682.55L135.55,682.94L136.26,682.25L135.29,681.74L135.44,680.92L135.14,680.17z"
},
{
"id":"RU-YAR",
"title":"Yaroslavl'",
"d":"M128.96,597.31L129.22,597.02L129.52,597.29L129.81,595.22L130.99,595.54L130.9,595.8L131.27,596.05L131.52,595.5L131.32,595.26L131.9,595.1L131.44,594.62L131.41,594.1L131.65,594.4L131.97,593.95L134.97,594.3L135.8,594.04L135.84,593.53L136.41,593.5L136.74,593.59L136.7,593.87L137.61,593.69L138.22,594.02L138.61,593.69L138.48,593.28L138.9,592.51L138.56,591.28L138.93,590.83L139.52,591.32L139.91,590.91L142.59,592.05L143.54,591.81L144.02,592.84L144.83,592.64L145.13,593.49L146.96,594.94L147.04,595.36L146.61,595.47L146.83,595.95L148.29,596.8L148.54,596.45L149.29,596.89L149.7,596.36L150.02,596.65L150.35,596.39L151.63,596.38L152,596.53L152,596.99L152.97,596.81L152.97,596.81L153.77,597.2L153.96,598.31L154.7,599.26L154.18,599.94L153.46,600.18L152.79,601.29L152.28,601.57L152.58,602.31L151.42,603.15L151.5,604.61L150.43,605.42L150.98,606.78L150.35,608.03L150.95,609.12L150.74,609.52L150.23,609.25L150.05,609.66L149.73,609.35L149.81,609.99L149.23,610.14L149.38,610.72L148.95,610.97L149.07,612.96L149.56,613.56L149.56,613.56L148.97,613.9L147.23,613.73L147.96,614.17L147.46,614.5L147.47,614.91L147.11,614.97L146.61,614.48L146.3,614.61L145.76,615.19L145.35,615.21L144.67,616.13L144.49,615.95L143.45,616.57L143.49,616.97L143.09,616.96L142.67,617.41L143.17,618.2L142.32,618.55L142.15,619.44L141.77,619.43L141.95,620.43L141.95,620.43L141.36,621.38L141.43,622.09L141.67,622.12L141.19,622.84L141.3,623.26L140.79,623.44L139.81,622.71L139.44,623.18L138.41,623.19L137.82,622.53L137.24,622.44L136.09,623.21L135.62,623.06L135.52,622.1L134.74,621.37L134.74,621.37L133.95,620.45L133.95,620.45L133.58,619.89L133.24,619.94L132.97,619.04L133.33,618.09L132.72,617.78L133.7,617.46L133.98,617.07L133.54,616.13L133.88,615.64L133.45,615.5L133.23,615.02L133.25,614.26L133.79,614.36L134.32,613.61L134.03,612.53L133.46,612.54L133.25,612.98L132.67,613.15L132.15,612.99L130.87,611.55L130.7,609.64L129.78,608.92L129.35,607.81L128.8,607.18L127.4,606.68L127.96,605.92L127.53,605.91L127.52,605.46L128.54,605.45L128.11,605.06L127.15,605.15L127.22,604.66L128.58,604.15L128.87,603.26L129.69,603.15L128.77,601.75L127.88,601.72L127.6,601.04L127.05,600.9L127.99,599.96L127.53,599.45L128,598.77L128.41,598.9L128.7,598.48L129.08,598.54L129.24,598.14z"
},
{
"id":"RU-YEV",
"title":"Yevrey",
"d":"M801.27,709.97L801.94,710.27L803.89,708.99L804.63,709.16L804.99,709.62L805.46,709.51L805.42,708.72L805.8,708.49L805.95,707.71L806.73,707.38L808.37,708.21L808.44,709.24L809.01,709.68L809.63,709.33L810.33,709.54L810.96,709.21L811.3,710.1L812.99,710.22L813.86,710.7L814.54,713.78L815.71,715.02L818.08,716.09L821.17,716.59L822.26,715.49L822.73,715.52L823.17,716.11L823.61,716.19L824.02,717.03L824.28,716.7L824.95,717.16L825.52,716.84L826.39,717.15L826.15,718.45L825.44,718.91L823.71,718.39L822.1,719.52L822.1,719.52L820.36,719.96L820.08,720.54L819.26,720.73L819.07,721.53L818.43,721.4L816.42,722.73L813.98,722.4L813.06,722.92L812.89,723.33L811.95,723.53L811.44,724.31L810.46,724.1L809.69,726.56L807.94,726.18L807.42,726.67L805.66,726.67L805.42,727.1L804.25,727.05L803.49,726.65L802.74,727.15L801.68,726.28L798.7,726.88L798.16,726.51L798.15,725.46L797.51,724.25L796.18,723.07L795.99,722.44L797.24,720.31L796.57,719L796.74,718.23L795.76,718.31L795.62,717.3L795.08,716.93L796.17,714.37L795.9,714.05L795.39,714.24L795.39,714.24L795.69,713.75L796.97,712.98L798.2,712.8L798.53,711.73L799.55,710.18L800.08,709.89z"
},
{
"id":"RU-ZAB",
"title":"Zabaykal'ye",
"d":"M732.95,662.19L729.93,663.39L729.07,663.4L728.35,663.89L727.66,663.99L727.29,663.65L725.86,663.83L724.5,665.18L724.11,666L723.41,666.4L721.63,668.83L719.81,669.95L720.01,670.74L719.79,671.61L720.05,672.17L720.92,672.25L721.55,671.75L722.86,671.49L724.78,672.65L723.99,674.94L724.06,675.35L725.04,676.15L724.9,676.59L725.19,677.15L724.93,678.08L724.49,678.5L724.69,679.02L724.25,679.83L723.61,680.02L723.48,680.4L723.01,680.35L722.87,680.81L720.87,682.68L720.28,682.73L719.92,684.17L719.41,684.88L719.52,685.32L718.9,686.09L719.1,686.44L718.22,687.26L718.25,687.98L717.89,688L717.79,689.46L716.13,691.55L715.89,693.44L714.41,694.97L714.17,696.69L713.28,697.43L713.72,697.87L714.97,697.93L715.08,698.25L714.71,698.64L715.05,699.78L714.75,700.56L713.78,701.63L709.31,702.55L708.75,703.57L708.05,703.68L707.99,704.21L706.98,704.69L706.41,705.49L706.07,705.48L704.23,707.2L701.53,705.85L700.07,705.81L697.63,704.78L696,703.58L695.28,702.39L692.61,701.37L691.34,701.64L689.21,702.98L686.63,702.81L685.47,701.96L683.51,699.57L681.67,698.91L679.85,699L679.09,698.57L676.84,699.66L675.65,700.79L675.01,700.73L672.96,702.01L670.84,703.81L670.14,706L667.66,707.35L665.93,706.75L661.78,708.41L660.06,708.31L658.68,708.98L657.8,708.65L656.03,709.61L654.76,710.73L653.55,711.13L652.19,710.97L650.77,709.91L650.25,710.65L649.5,710.94L647.1,710.45L646.79,710.65L646.16,710.26L644.61,710.27L644.21,709.59L642.31,708.79L641.04,709.06L640.49,708.81L637.47,709.06L635.61,706.95L634.56,706.61L633.75,705.99L633.66,705.33L633.18,705.31L633.44,704.57L633.19,703.33L633.39,702.61L632.53,702.6L631.72,701.92L631.72,701.92L631.56,700.98L632.89,700.1L633.45,698.76L634.04,698.85L634.96,698.03L635.76,697.89L636.86,697.14L637.92,697.42L638.27,696.6L637.24,696.49L636.66,695.68L634.95,695.1L634.22,694.35L634.39,693.83L635.34,693.33L635.68,690.39L636.74,690.12L637.51,689.42L636.24,688.42L636.84,687.31L637.05,686.01L637.43,686.2L637.76,685.98L637.84,684.96L638.68,685.54L641.14,685.4L641.23,685.83L642.51,686.49L645.27,685.61L646.5,684.29L647.66,683.69L650.44,683.78L650.87,684.6L652.62,684.8L653.72,683.97L653.94,682.9L654.87,682.24L655.38,681.32L659.54,679.69L662.66,675.74L663.33,675.56L663.63,675.97L665.17,676.3L665.97,675.11L666.57,674.85L668.89,674.98L670.31,673.78L673.48,673.44L674.97,671.66L677.06,671.06L678.27,669.36L678.38,668.12L678.69,667.96L678.92,666.46L677.8,666.28L677.53,665.98L678,665.51L677.86,664.78L677.33,664.84L676.19,663.96L676.18,663.01L675.49,662.34L675.48,659.88L676.47,658.69L678.9,657.86L679.11,657.47L680.15,657.47L681.02,655.85L682.73,655.2L685.37,652.85L687.05,651.92L687.83,650.44L692.95,648.93L694.49,649.08L694.8,648.78L696.04,648.63L696.76,647.69L696.75,646.97L697.15,646.68L697.75,644.46L696.85,641.9L695.38,640.88L693.89,638.67L692.25,638.78L690.65,638.23L690.41,634.65L689.9,633.13L690.1,631.47L689.49,630.13L689.91,628.19L688.88,625.76L688.89,624.96L689.49,624.79L689.4,624.35L689.05,624.1L688.71,622.95L687.08,622.07L688.25,620.88L688.04,619.02L689.2,617.95L689.2,617.95L689.52,617.85L691.11,618.73L691.92,619.49L692.72,618.94L693.13,619.01L694.27,620.02L696.07,620.13L696.42,620.45L697.18,619.9L697.94,620L697.82,619.48L698.5,619.71L698.79,619.53L699.17,618.56L699.98,617.76L700.99,619.21L701.48,618.96L701.95,619.27L702.27,618.64L702.09,617.98L702.47,617.79L702.86,616.25L702.24,615.12L703.01,614.78L703.31,613.82L703.79,613.57L702.57,612.94L702.11,613L702,613.57L701.17,614.15L700.72,613.76L701.12,613.16L700.99,612.67L700.41,612.72L700.41,611.3L699.81,610.89L699.56,610.28L700.15,608.99L699.3,608.92L698.92,608.3L699.31,607.54L699.06,606.67L698.62,606.37L698.97,605.97L700.21,606.03L700.42,605.45L700.78,605.35L700.57,604.82L701.02,603.02L700.86,602.22L701.24,601.63L701.77,602.21L702.22,602.03L701.91,600.62L701.17,600.07L701.42,599.5L702.56,599.03L703.13,598.25L703.74,598.22L705.3,598.91L705.88,598.64L706.62,598.83L707.4,599.4L708.46,600.91L709.84,601.58L713.08,600.94L713.08,600.94L713.4,603.33L713.01,604.2L712.5,607.65L713.25,608.05L713.49,608.7L713.36,609.78L713.76,610.51L714.16,610.18L714.2,609.34L714.68,609.14L715.64,609.63L715.25,611.77L717.2,615.15L716.76,615.72L717.01,617.55L718.05,618.54L718.05,618.54L718.12,618.93L716.91,620.11L716.99,620.53L718.33,621.25L718.46,621.58L718.05,621.87L717.98,622.45L719.1,623.31L719.22,623.88L721.63,624.38L721.45,625.25L722.17,625.52L722.16,626.21L723.13,626.72L722.91,627.1L720.9,627.41L720.03,628.26L720.14,631.41L720.39,631.66L721.67,631.14L722.16,631.67L722.79,631.58L723.35,631.13L724.01,631.14L724.56,630.52L725.13,630.5L725.58,629.94L728.25,630.02L728.58,630.49L728.56,631.96L728.95,632.46L728.74,633.52L729.25,635.26L729.01,635.91L729.45,636.52L730.74,636.81L731.29,636.4L731.67,635.24L732.17,635.2L733.28,636.09L733.71,637.02L733.86,637.99L733.34,640.24L734.26,640.46L733.62,641.08L733.62,642.62L731.88,644.47L731.6,645.59L731.67,646.15L732.13,645.67L732.98,645.49L733.21,646.03L732.97,647L733.45,648.15L733.84,648.79L734.62,649.22L734.52,649.7L733.2,650.33L732.72,650.32L732.46,649.68L731.81,650.1L731.51,650.66L732.03,652.79L731.34,653.72L731.27,654.68L732,655.77L732.19,655.37L732.5,655.54L733.56,657.41L733.61,660.63L733.99,660.87L734.33,662.22L734.33,662.22z"
}
]
}
}
}; | rickyalex/cts | assets_/global/plugins/amcharts/ammap/maps/js/russiaHigh.js | JavaScript | mit | 319,365 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Acl\Tests\Permission;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;
class MaskBuilderTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \InvalidArgumentException
* @dataProvider getInvalidConstructorData
*/
public function testConstructorWithNonInteger($invalidMask)
{
new MaskBuilder($invalidMask);
}
public function getInvalidConstructorData()
{
return array(
array(234.463),
array('asdgasdf'),
array(array()),
array(new \stdClass()),
);
}
public function testConstructorWithoutArguments()
{
$builder = new MaskBuilder();
$this->assertEquals(0, $builder->get());
}
public function testConstructor()
{
$builder = new MaskBuilder(123456);
$this->assertEquals(123456, $builder->get());
}
public function testAddAndRemove()
{
$builder = new MaskBuilder();
$builder
->add('view')
->add('eDiT')
->add('ownEr')
;
$mask = $builder->get();
$this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW);
$this->assertEquals(MaskBuilder::MASK_EDIT, $mask & MaskBuilder::MASK_EDIT);
$this->assertEquals(MaskBuilder::MASK_OWNER, $mask & MaskBuilder::MASK_OWNER);
$this->assertEquals(0, $mask & MaskBuilder::MASK_MASTER);
$this->assertEquals(0, $mask & MaskBuilder::MASK_CREATE);
$this->assertEquals(0, $mask & MaskBuilder::MASK_DELETE);
$this->assertEquals(0, $mask & MaskBuilder::MASK_UNDELETE);
$builder->remove('edit')->remove('OWner');
$mask = $builder->get();
$this->assertEquals(0, $mask & MaskBuilder::MASK_EDIT);
$this->assertEquals(0, $mask & MaskBuilder::MASK_OWNER);
$this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW);
}
public function testGetPattern()
{
$builder = new MaskBuilder();
$this->assertEquals(MaskBuilder::ALL_OFF, $builder->getPattern());
$builder->add('view');
$this->assertEquals(str_repeat('.', 31).'V', $builder->getPattern());
$builder->add('owner');
$this->assertEquals(str_repeat('.', 24).'N......V', $builder->getPattern());
$builder->add(1 << 10);
$this->assertEquals(str_repeat('.', 21).MaskBuilder::ON.'..N......V', $builder->getPattern());
}
public function testReset()
{
$builder = new MaskBuilder();
$this->assertEquals(0, $builder->get());
$builder->add('view');
$this->assertTrue($builder->get() > 0);
$builder->reset();
$this->assertEquals(0, $builder->get());
}
}
| groundcall/jobeet | vendor/symfony/symfony/src/Symfony/Component/Security/Acl/Tests/Permission/MaskBuilderTest.php | PHP | mit | 3,041 |
/*!
Copyright (C) 2011 T. Connell & Associates, Inc.
Dual-licensed under the MIT and GPL licenses
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Resizable scroller widget for the jQuery tablesorter plugin
Version 2.0 - modified by Rob Garrison 4/12/2013; updated 6/28/2014 (v2.17.3)
Requires jQuery v1.7+
Requires the tablesorter plugin, v2.8+, available at http://mottie.github.com/tablesorter/docs/
Usage:
$(function() {
$('table.tablesorter').tablesorter({
widgets: ['zebra', 'scroller'],
widgetOptions : {
scroller_height : 300, // height of scroll window
scroller_barWidth : 18, // scroll bar width
scroller_jumpToHeader : true, // header snap to browser top when scrolling the tbody
scroller_idPrefix : 's_' // cloned thead id prefix (random number added to end)
}
});
});
Website: www.tconnell.com
*/
/*jshint browser:true, jquery:true, unused:false */
;(function($){
"use strict";
$.fn.hasScrollBar = function(){
return this.get(0).scrollHeight > this.height();
};
var ts = $.tablesorter;
ts.window_resize = function(){
if (this.resize_timer) {
clearTimeout(this.resize_timer);
}
this.resize_timer = setTimeout(function(){
$(this).trigger('resizeEnd');
}, 250);
};
// Add extra scroller css
$(function(){
var s = '<style>' +
'.tablesorter-scroller-reset { width: auto !important; } ' +
'.tablesorter-scroller { text-align: left; overflow: hidden; }' +
'.tablesorter-scroller-header { overflow: hidden; }' +
'.tablesorter-scroller-header table.tablesorter { margin-bottom: 0; }' +
'.tablesorter-scroller-table { overflow-y: scroll; }' +
'.tablesorter-scroller-table table.tablesorter { margin-top: 0; overflow: scroll; } ' +
'.tablesorter-scroller-table .tablesorter-filter-row, .tablesorter-scroller-table tfoot { display: none; }' +
'.tablesorter-scroller-table table.tablesorter thead tr.tablesorter-headerRow * {' +
'line-height:0;height:0;border:none;background-image:none;padding-top:0;padding-bottom:0;margin-top:0;margin-bottom:0;overflow:hidden;' +
'}</style>';
$(s).appendTo('body');
});
ts.addWidget({
id: 'scroller',
priority: 60, // run after the filter widget
options: {
scroller_height : 300,
scroller_barWidth : 18,
scroller_jumpToHeader: true,
scroller_upAfterSort: true,
scroller_idPrefix : 's_'
},
init: function(table, thisWidget, c, wo){
var $win = $(window);
// Setup window.resizeEnd event
$win
.bind('resize', ts.window_resize)
.bind('resizeEnd', function() {
// init is run before format, so scroller_resizeWidth
// won't be defined within the "c" or "wo" parameters
if (typeof table.config.widgetOptions.scroller_resizeWidth === 'function') {
// IE calls resize when you modify content, so we have to unbind the resize event
// so we don't end up with an infinite loop. we can rebind after we're done.
$win.unbind('resize', ts.window_resize);
table.config.widgetOptions.scroller_resizeWidth();
$win.bind('resize', ts.window_resize);
}
});
},
format: function(table, c, wo) {
var h, $hdr, id, t, resize, $cells,
$win = $(window),
$tbl = c.$table;
if (!c.isScrolling) {
h = wo.scroller_height || 300;
t = $tbl.find('tbody').height();
if (t !== 0 && h > t) { h = t + 10; } // Table is less than h px
id = wo.scroller_id = wo.scroller_idPrefix + Math.floor(Math.random() * 1001);
$hdr = $('<table class="' + $tbl.attr('class') + '" cellpadding=0 cellspacing=0><thead>' + $tbl.find('thead:first').html() + '</thead></table>');
$tbl
.wrap('<div id="' + id + '" class="tablesorter-scroller" />')
.before($hdr)
.find('.tablesorter-filter-row').addClass('hideme');
$cells = $hdr
.wrap('<div class="tablesorter-scroller-header" style="width:' + $tbl.width() + ';" />')
.find('.' + ts.css.header);
$tbl.wrap('<div class="tablesorter-scroller-table" style="height:' + h + 'px;width:' + $tbl.width() + ';" />');
// make scroller header sortable
ts.bindEvents(table, $cells);
// look for filter widget
if ($tbl.hasClass('hasFilters')) {
ts.filter.bindSearch( $tbl, $hdr.find('.' + ts.css.filter) );
}
resize = function(){
var d, b, $h, $th, w,
// Hide other scrollers so we can resize
$div = $('div.scroller[id != "' + id + '"]').hide();
$tbl.find('thead').show();
// Reset sizes so parent can resize.
$tbl
.addClass('tablesorter-scroller-reset')
.find('thead').find('.tablesorter-header-inner').addClass('tablesorter-scroller-reset');
d = $tbl.parent();
d.addClass('tablesorter-scroller-reset');
d.parent().trigger('resize');
// Shrink a bit to accommodate scrollbar
d.width( d.parent().innerWidth() - ( d.parent().hasScrollBar() ? wo.scroller_barWidth : 0 ) );
w = d.innerWidth() - ( d.hasScrollBar() ? wo.scroller_barWidth : 0 );
$tbl.width( w );
$hdr.width( w );
$hdr.parent().width( w );
$tbl.closest('.tablesorter-scroller').find('.tablesorter-scroller-reset').removeClass('tablesorter-scroller-reset');
// include left & right border widths
b = parseInt( $tbl.css('border-left-width'), 10 ) + parseInt( $tbl.css('border-right-width'), 10 );
$h = $hdr.find('thead').children().children();
// adjust cloned header to match original table width - includes wrappers, headers, and header inner div
$tbl.find('thead').children().children().each(function(i, c){
$th = $(c).find('.tablesorter-header-inner');
if ($th.length) {
// I have no idea why this is in here anymore LOL
w = parseInt( $th.css('min-width').replace('auto', '0').replace(/(px|em)/, ''), 10 );
if ( $th.width() < w ) {
$th.width(w);
} else {
w = $th.width();
}
$h.eq(i)
.find('.tablesorter-header-inner').width(w - b)
// set inner width first
.parent()
.width( $th.parent().width() - b );
}
});
$div.show();
};
// Expose to external calls
wo.scroller_resizeWidth = resize;
resize();
$tbl.find('thead').css('visibility', 'hidden');
c.isScrolling = true;
t = $tbl.parent().parent().height();
// The header will always jump into view if scrolling the table body
$tbl.parent().bind('scroll', function(){
if (wo.scroller_jumpToHeader) {
var pos = $win.scrollTop() - $hdr.offset().top;
if ($(this).scrollTop() !== 0 && pos < t && pos > 0) {
$win.scrollTop( $hdr.offset().top );
}
}
$hdr.parent().scrollLeft( $(this).scrollLeft() );
});
}
// Sorting, so scroll to top
if (wo.scroller_upAfterSort) {
$tbl.parent().animate({ scrollTop: 0 }, 'fast');
}
},
remove : function(table, c, wo){
var $table = c.$table;
$table.closest('.tablesorter-scroller').find('.tablesorter-scroller-header').remove();
$table
.unwrap()
.find('.tablesorter-filter-row').removeClass('hideme').end()
.find('thead').show().css('visibility', 'visible');
c.isScrolling = false;
}
});
})(jQuery);
| sitic/cdnjs | ajax/libs/jquery.tablesorter/2.17.7/js/widgets/widget-scroller.js | JavaScript | mit | 7,448 |
define(function(){
// pt-BR (Brazillian Portuguese)
return {
"am" : "",
"pm" : "",
"x": "%d/%m/%y",
"X": "%H:%M:%S",
"c": "%a %d %b %Y %H:%M:%S %Z",
"months" : [
"Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro"
],
"months_abbr" : [
"Jan",
"Fev",
"Mar",
"Abr",
"Mai",
"Jun",
"Jul",
"Ago",
"Set",
"Out",
"Nov",
"Dez"
],
"days" : [
"Domingo",
"Segunda",
"Terça",
"Quarta",
"Quinta",
"Sexta",
"Sábado"
],
"days_abbr" : [
"Dom",
"Seg",
"Ter",
"Qua",
"Qui",
"Sex",
"Sáb"
]
};
});
| MikeLockz/exit-now-mobile | node_modules/bower/node_modules/mout/src/date/i18n/pt-BR.js | JavaScript | mit | 1,130 |
(function() {
var DEFAULT_BRACKETS = "()[]{}''\"\"";
var DEFAULT_EXPLODE_ON_ENTER = "[]{}";
var SPACE_CHAR_REGEX = /\s/;
CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
if (old != CodeMirror.Init && old)
cm.removeKeyMap("autoCloseBrackets");
if (!val) return;
var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER;
if (typeof val == "string") pairs = val;
else if (typeof val == "object") {
if (val.pairs != null) pairs = val.pairs;
if (val.explode != null) explode = val.explode;
}
var map = buildKeymap(pairs);
if (explode) map.Enter = buildExplodeHandler(explode);
cm.addKeyMap(map);
});
function charsAround(cm, pos) {
var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1),
CodeMirror.Pos(pos.line, pos.ch + 1));
return str.length == 2 ? str : null;
}
function buildKeymap(pairs) {
var map = {
name : "autoCloseBrackets",
Backspace: function(cm) {
if (cm.somethingSelected()) return CodeMirror.Pass;
var cur = cm.getCursor(), around = charsAround(cm, cur);
if (around && pairs.indexOf(around) % 2 == 0)
cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
else
return CodeMirror.Pass;
}
};
var closingBrackets = "";
for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
if (left != right) closingBrackets += right;
function surround(cm) {
var selection = cm.getSelection();
cm.replaceSelection(left + selection + right);
}
function maybeOverwrite(cm) {
var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass;
else cm.execCommand("goCharRight");
}
map["'" + left + "'"] = function(cm) {
if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment")
return CodeMirror.Pass;
if (cm.somethingSelected()) return surround(cm);
if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : "";
if (left == right && CodeMirror.isWordChar(curChar))
return CodeMirror.Pass;
if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
else
return CodeMirror.Pass;
};
if (left != right) map["'" + right + "'"] = maybeOverwrite;
})(pairs.charAt(i), pairs.charAt(i + 1));
return map;
}
function buildExplodeHandler(pairs) {
return function(cm) {
var cur = cm.getCursor(), around = charsAround(cm, cur);
if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
cm.operation(function() {
var newPos = CodeMirror.Pos(cur.line + 1, 0);
cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input");
cm.indentLine(cur.line + 1, null, true);
cm.indentLine(cur.line + 2, null, true);
});
};
}
})();
| binaek89/cdnjs | ajax/libs/codemirror/3.18.0/addon/edit/closebrackets.js | JavaScript | mit | 3,381 |
[{"locale":"en"},{"category":"Lu","mappings":{"default":{"default":"double struck capital a","short":"double struck cap a"},"mathspeak":{"default":"double struck upper A"}},"key":"1D538"},{"category":"Lu","mappings":{"default":{"default":"double struck capital b","short":"double struck cap b"},"mathspeak":{"default":"double struck upper B"}},"key":"1D539"},{"category":"Lu","mappings":{"default":{"default":"double struck capital c","short":"double struck cap c"},"mathspeak":{"default":"double struck upper C"}},"key":"2102"},{"category":"Lu","mappings":{"default":{"default":"double struck capital d","short":"double struck cap d"},"mathspeak":{"default":"double struck upper D"}},"key":"1D53B"},{"category":"Lu","mappings":{"default":{"default":"double struck capital e","short":"double struck cap e"},"mathspeak":{"default":"double struck upper E"}},"key":"1D53C"},{"category":"Lu","mappings":{"default":{"default":"double struck capital f","short":"double struck cap f"},"mathspeak":{"default":"double struck upper F"}},"key":"1D53D"},{"category":"Lu","mappings":{"default":{"default":"double struck capital g","short":"double struck cap g"},"mathspeak":{"default":"double struck upper G"}},"key":"1D53E"},{"category":"Lu","mappings":{"default":{"default":"double struck capital h","short":"double struck cap h"},"mathspeak":{"default":"double struck upper H"}},"key":"210D"},{"category":"Lu","mappings":{"default":{"default":"double struck capital i","short":"double struck cap i"},"mathspeak":{"default":"double struck upper I"}},"key":"1D540"},{"category":"Lu","mappings":{"default":{"default":"double struck capital j","short":"double struck cap j"},"mathspeak":{"default":"double struck upper J"}},"key":"1D541"},{"category":"Lu","mappings":{"default":{"default":"double struck capital k","short":"double struck cap k"},"mathspeak":{"default":"double struck upper K"}},"key":"1D542"},{"category":"Lu","mappings":{"default":{"default":"double struck capital l","short":"double struck cap l"},"mathspeak":{"default":"double struck upper L"}},"key":"1D543"},{"category":"Lu","mappings":{"default":{"default":"double struck capital m","short":"double struck cap m"},"mathspeak":{"default":"double struck upper M"}},"key":"1D544"},{"category":"Lu","mappings":{"default":{"default":"double struck capital n","short":"double struck cap n"},"mathspeak":{"default":"double struck upper N"}},"key":"2115"},{"category":"Lu","mappings":{"default":{"default":"double struck capital o","short":"double struck cap o"},"mathspeak":{"default":"double struck upper O"}},"key":"1D546"},{"category":"Lu","mappings":{"default":{"default":"double struck capital p","short":"double struck cap p"},"mathspeak":{"default":"double struck upper P"}},"key":"2119"},{"category":"Lu","mappings":{"default":{"default":"double struck capital q","short":"double struck cap q"},"mathspeak":{"default":"double struck upper Q"}},"key":"211A"},{"category":"Lu","mappings":{"default":{"default":"double struck capital r","short":"double struck cap r"},"mathspeak":{"default":"double struck upper R"}},"key":"211D"},{"category":"Lu","mappings":{"default":{"default":"double struck capital s","short":"double struck cap s"},"mathspeak":{"default":"double struck upper S"}},"key":"1D54A"},{"category":"Lu","mappings":{"default":{"default":"double struck capital t","short":"double struck cap t"},"mathspeak":{"default":"double struck upper T"}},"key":"1D54B"},{"category":"Lu","mappings":{"default":{"default":"double struck capital u","short":"double struck cap u"},"mathspeak":{"default":"double struck upper U"}},"key":"1D54C"},{"category":"Lu","mappings":{"default":{"default":"double struck capital v","short":"double struck cap v"},"mathspeak":{"default":"double struck upper V"}},"key":"1D54D"},{"category":"Lu","mappings":{"default":{"default":"double struck capital w","short":"double struck cap w"},"mathspeak":{"default":"double struck upper W"}},"key":"1D54E"},{"category":"Lu","mappings":{"default":{"default":"double struck capital x","short":"double struck cap x"},"mathspeak":{"default":"double struck upper X"}},"key":"1D54F"},{"category":"Lu","mappings":{"default":{"default":"double struck capital y","short":"double struck cap y"},"mathspeak":{"default":"double struck upper Y"}},"key":"1D550"},{"category":"Lu","mappings":{"default":{"default":"double struck capital z","short":"double struck cap z"},"mathspeak":{"default":"double struck upper Z"}},"key":"2124"},{"category":"Ll","mappings":{"default":{"default":"double struck small a","short":"double struck a"}},"key":"1D552"},{"category":"Ll","mappings":{"default":{"default":"double struck small b","short":"double struck b"}},"key":"1D553"},{"category":"Ll","mappings":{"default":{"default":"double struck small c","short":"double struck c"}},"key":"1D554"},{"category":"Ll","mappings":{"default":{"default":"double struck small d","short":"double struck d"}},"key":"1D555"},{"category":"Ll","mappings":{"default":{"default":"double struck small e","short":"double struck e"}},"key":"1D556"},{"category":"Ll","mappings":{"default":{"default":"double struck small f","short":"double struck f"}},"key":"1D557"},{"category":"Ll","mappings":{"default":{"default":"double struck small g","short":"double struck g"}},"key":"1D558"},{"category":"Ll","mappings":{"default":{"default":"double struck small h","short":"double struck h"}},"key":"1D559"},{"category":"Ll","mappings":{"default":{"default":"double struck small i","short":"double struck i"}},"key":"1D55A"},{"category":"Ll","mappings":{"default":{"default":"double struck small j","short":"double struck j"}},"key":"1D55B"},{"category":"Ll","mappings":{"default":{"default":"double struck small k","short":"double struck k"}},"key":"1D55C"},{"category":"Ll","mappings":{"default":{"default":"double struck small l","short":"double struck l"}},"key":"1D55D"},{"category":"Ll","mappings":{"default":{"default":"double struck small m","short":"double struck m"}},"key":"1D55E"},{"category":"Ll","mappings":{"default":{"default":"double struck small n","short":"double struck n"}},"key":"1D55F"},{"category":"Ll","mappings":{"default":{"default":"double struck small o","short":"double struck o"}},"key":"1D560"},{"category":"Ll","mappings":{"default":{"default":"double struck small p","short":"double struck p"}},"key":"1D561"},{"category":"Ll","mappings":{"default":{"default":"double struck small q","short":"double struck q"}},"key":"1D562"},{"category":"Ll","mappings":{"default":{"default":"double struck small r","short":"double struck r"}},"key":"1D563"},{"category":"Ll","mappings":{"default":{"default":"double struck small s","short":"double struck s"}},"key":"1D564"},{"category":"Ll","mappings":{"default":{"default":"double struck small t","short":"double struck t"}},"key":"1D565"},{"category":"Ll","mappings":{"default":{"default":"double struck small u","short":"double struck u"}},"key":"1D566"},{"category":"Ll","mappings":{"default":{"default":"double struck small v","short":"double struck v"}},"key":"1D567"},{"category":"Ll","mappings":{"default":{"default":"double struck small w","short":"double struck w"}},"key":"1D568"},{"category":"Ll","mappings":{"default":{"default":"double struck small x","short":"double struck x"}},"key":"1D569"},{"category":"Ll","mappings":{"default":{"default":"double struck small y","short":"double struck y"}},"key":"1D56A"},{"category":"Ll","mappings":{"default":{"default":"double struck small z","short":"double struck z"}},"key":"1D56B"}]
| jonobr1/cdnjs | ajax/libs/mathjax/2.7.5/extensions/a11y/mathmaps/en/symbols/latin-mathfonts-double-struck.js | JavaScript | mit | 7,499 |
.element-animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
}
.element-animated.short {
-webkit-animation-duration: .5s;
animation-duration: .5s;
}
.element-animated.long {
-webkit-animation-duration: 2s;
animation-duration: 2s;
}
.element-animated.infinite {
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
@-webkit-keyframes slide-from-right {
0% {
-webkit-transform: translateX(200px);
transform: translateX(200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-right {
0% {
-webkit-transform: translateX(200px);
transform: translateX(200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-right {
-webkit-animation-name: slide-from-right;
animation-name: slide-from-right;
}
@-webkit-keyframes slide-from-left {
0% {
-webkit-transform: translateX(-200px);
transform: translateX(-200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-left {
0% {
-webkit-transform: translateX(-200px);
transform: translateX(-200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-left {
-webkit-animation-name: slide-from-left;
animation-name: slide-from-left;
}
@-webkit-keyframes slide-from-top {
0% {
-webkit-transform: translateY(-200px);
transform: translateY(-200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-top {
0% {
-webkit-transform: translateY(-200px);
transform: translateY(-200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-top {
-webkit-animation-name: slide-from-top;
animation-name: slide-from-top;
}
@-webkit-keyframes slide-from-bottom {
0% {
-webkit-transform: translateY(200px);
transform: translateY(200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-bottom {
0% {
-webkit-transform: translateY(200px);
transform: translateY(200px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-bottom {
-webkit-animation-name: slide-from-bottom;
animation-name: slide-from-bottom;
}
@-webkit-keyframes slide-from-right-bottom {
0% {
-webkit-transform: translate(100px, 100px);
transform: translate(100px, 100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-right-bottom {
0% {
-webkit-transform: translate(100px, 100px);
transform: translate(100px, 100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-right-bottom {
-webkit-animation-name: slide-from-right-bottom;
animation-name: slide-from-right-bottom;
}
@-webkit-keyframes slide-from-left-bottom {
0% {
-webkit-transform: translate(-100px, 100px);
transform: translate(-100px, 100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-left-bottom {
0% {
-webkit-transform: translate(-100px, 100px);
transform: translate(-100px, 100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-left-bottom {
-webkit-animation-name: slide-from-left-bottom;
animation-name: slide-from-left-bottom;
}
@-webkit-keyframes slide-from-right-top {
0% {
-webkit-transform: translate(100px, -100px);
transform: translate(100px, -100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-right-top {
0% {
-webkit-transform: translate(100px, -100px);
transform: translate(100px, -100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-right-top {
-webkit-animation-name: slide-from-right-top;
animation-name: slide-from-right-top;
}
@-webkit-keyframes slide-from-left-top {
0% {
-webkit-transform: translate(-100px, -100px);
transform: translate(-100px, -100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes slide-from-left-top {
0% {
-webkit-transform: translate(-100px, -100px);
transform: translate(-100px, -100px);
}
100% {
-webkit-transform: none;
transform: none;
}
}
.slide-from-left-top {
-webkit-animation-name: slide-from-left-top;
animation-name: slide-from-left-top;
}
@-webkit-keyframes slide-left-right {
0% {
-webkit-transform: translateX(-100px);
transform: translateX(-100px);
}
50% {
-webkit-transform: none;
transform: none;
}
100% {
-webkit-transform: translateX(100px);
transform: translateX(100px);
}
}
@keyframes slide-left-right {
0% {
-webkit-transform: translateX(-100px);
transform: translateX(-100px);
}
50% {
-webkit-transform: none;
transform: none;
}
100% {
-webkit-transform: translateX(100px);
transform: translateX(100px);
}
}
.slide-left-right {
-webkit-animation-name: slide-left-right;
animation-name: slide-left-right;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-direction: alternate;
animation-direction: alternate;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
@-webkit-keyframes slide-top-bottom {
0% {
-webkit-transform: translateY(-100px);
transform: translateY(-100px);
}
50% {
-webkit-transform: none;
transform: none;
}
100% {
-webkit-transform: translateY(100px);
transform: translateY(100px);
}
}
@keyframes slide-top-bottom {
0% {
-webkit-transform: translateY(-100px);
transform: translateY(-100px);
}
50% {
-webkit-transform: none;
transform: none;
}
100% {
-webkit-transform: translateY(100px);
transform: translateY(100px);
}
}
.slide-top-bottom {
-webkit-animation-name: slide-top-bottom;
animation-name: slide-top-bottom;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-direction: alternate;
animation-direction: alternate;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
@-webkit-keyframes tremble {
0%, 20%, 40%, 60%, 80%, 100% {
-webkit-transform: translateX(5px);
transform: translateX(5px);
}
10%, 30%, 50%, 70%, 90% {
-webkit-transform: none;
transform: none;
}
}
@keyframes tremble {
0%, 20%, 40%, 60%, 80%, 100% {
-webkit-transform: translateX(5px);
transform: translateX(5px);
}
10%, 30%, 50%, 70%, 90% {
-webkit-transform: none;
transform: none;
}
}
.tremble {
-webkit-animation-name: tremble;
animation-name: tremble;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
@-webkit-keyframes fade-out {
0% {
opacity: .8;
}
100% {
opacity: 0;
}
}
@keyframes fade-out {
0% {
opacity: .8;
}
100% {
opacity: 0;
}
}
.fade-out {
-webkit-animation-name: fade-out;
animation-name: fade-out;
}
@-webkit-keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: .8;
}
}
@keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: .8;
}
}
.fade-in {
-webkit-animation-name: fade-in;
animation-name: fade-in;
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
@-webkit-keyframes pulsate {
0%, 100% {
opacity: .8;
}
50% {
opacity: .6;
}
}
@keyframes pulsate {
0%, 100% {
opacity: .8;
}
50% {
opacity: .6;
}
}
.pulsate {
-webkit-animation-name: pulsate;
animation-name: pulsate;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
-webkit-animation-direction: alternate;
animation-direction: alternate;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
@-webkit-keyframes rotate {
0% {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn);
}
50% {
-webkit-transform: none;
transform: none;
}
}
@keyframes rotate {
0% {
-webkit-transform: rotate(-1turn);
transform: rotate(-1turn);
}
50% {
-webkit-transform: none;
transform: none;
}
}
.rotate {
-webkit-animation-name: rotate;
animation-name: rotate;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
}
| wout/cdnjs | ajax/libs/Repaintless.css/1.2.0/repaintless.css | CSS | mit | 9,159 |
/**
* Represents a user's presence.
*/
class Presence {
constructor(data = {}) {
/**
* The status of the presence:
*
* * **`online`** - user is online
* * **`offline`** - user is offline or invisible
* * **`idle`** - user is AFK
* * **`dnd`** - user is in Do not Disturb
* @type {string}
*/
this.status = data.status || 'offline';
/**
* The game that the user is playing
* @type {?Game}
*/
this.game = data.game ? new Game(data.game) : null;
}
update(data) {
this.status = data.status || this.status;
this.game = data.game ? new Game(data.game) : null;
}
/**
* Whether this presence is equal to another
* @param {Presence} presence The presence to compare with
* @returns {boolean}
*/
equals(presence) {
return this === presence || (
presence &&
this.status === presence.status &&
this.game ? this.game.equals(presence.game) : !presence.game
);
}
}
/**
* Represents a game that is part of a user's presence.
*/
class Game {
constructor(data) {
/**
* The name of the game being played
* @type {string}
*/
this.name = data.name;
/**
* The type of the game status
* @type {number}
*/
this.type = data.type;
/**
* If the game is being streamed, a link to the stream
* @type {?string}
*/
this.url = data.url || null;
}
/**
* Whether or not the game is being streamed
* @type {boolean}
* @readonly
*/
get streaming() {
return this.type === 1;
}
/**
* Whether this game is equal to another game
* @param {Game} game The game to compare with
* @returns {boolean}
*/
equals(game) {
return this === game || (
game &&
this.name === game.name &&
this.type === game.type &&
this.url === game.url
);
}
}
exports.Presence = Presence;
exports.Game = Game;
| Kurobatto/Frog-Bot | node_modules/discord.js/src/structures/Presence.js | JavaScript | mit | 1,929 |
<?php
/*
* This file is part of the symfony package.
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) Jonathan H. Wage <jonwage@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\DoctrineORMAdminBundle\Datagrid;
use Sonata\AdminBundle\Datagrid\Pager as BasePager;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
/**
* Doctrine pager class.
*
* @author Jonathan H. Wage <jonwage@gmail.com>
*/
class Pager extends BasePager
{
protected $queryBuilder = null;
/**
* {@inheritdoc}
*/
public function computeNbResult()
{
$countQuery = clone $this->getQuery();
if (count($this->getParameters()) > 0) {
$countQuery->setParameters($this->getParameters());
}
$countQuery->select(sprintf('count(DISTINCT %s.%s) as cnt', $countQuery->getRootAlias(), current($this->getCountColumn())));
return $countQuery->resetDQLPart('orderBy')->getQuery()->getSingleScalarResult();
}
/**
* {@inheritdoc}
*/
public function getResults($hydrationMode = Query::HYDRATE_OBJECT)
{
return $this->getQuery()->execute(array(), $hydrationMode);
}
/**
* {@inheritdoc}
*/
public function getQuery()
{
return $this->query;
}
/**
* {@inheritdoc}
*/
public function init()
{
$this->resetIterator();
$this->setNbResults($this->computeNbResult());
$this->getQuery()->setFirstResult(null);
$this->getQuery()->setMaxResults(null);
if (count($this->getParameters()) > 0) {
$this->getQuery()->setParameters($this->getParameters());
}
if (0 == $this->getPage() || 0 == $this->getMaxPerPage() || 0 == $this->getNbResults()) {
$this->setLastPage(0);
} else {
$offset = ($this->getPage() - 1) * $this->getMaxPerPage();
$this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
$this->getQuery()->setFirstResult($offset);
$this->getQuery()->setMaxResults($this->getMaxPerPage());
}
}
}
| andreymaznyak/ontologydatabase | vendor/sonata-project/doctrine-orm-admin-bundle/Datagrid/Pager.php | PHP | mit | 2,236 |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Linq;
using System.Xml;
using Umbraco.Core;
using Umbraco.Web.WebServices;
using umbraco.BusinessLogic;
namespace umbraco.webservices
{
public class Settings : UmbracoAuthorizedWebService
{
[WebMethod]
public XmlNode GetTabs(string ContextID, int ContentTypeId)
{
if (!AuthorizeRequest(DefaultApps.settings.ToString()))
{
var xmlDoc = new XmlDocument();
var tabs = xmlDoc.CreateElement("tabs");
foreach (var t in new cms.businesslogic.ContentType(ContentTypeId).getVirtualTabs.ToList())
{
var mXml = xmlDoc.CreateElement("tab");
mXml.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "id", t.Id.ToString()));
mXml.Attributes.Append(XmlHelper.AddAttribute(xmlDoc, "caption", t.Caption));
tabs.AppendChild(mXml);
}
return tabs;
}
return null;
}
}
}
| Spijkerboer/Umbraco-CMS | src/Umbraco.Web/umbraco.presentation/umbraco/webservices/Settings.asmx.cs | C# | mit | 1,074 |
// Copyright (c) 2013-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "consensus/validation.h"
#include "data/sighash.json.h"
#include "hash.h"
#include "validation.h" // For CheckTransaction
#include "script/interpreter.h"
#include "script/script.h"
#include "serialize.h"
#include "streams.h"
#include "test/test_bitcoin.h"
#include "test/test_random.h"
#include "util.h"
#include "utilstrencodings.h"
#include "version.h"
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
extern UniValue read_json(const std::string& jsondata);
// Old script.cpp SignatureHash function
uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
if (nIn >= txTo.vin.size())
{
printf("ERROR: SignatureHash(): nIn=%d out of range\n", nIn);
return one;
}
CMutableTransaction txTmp(txTo);
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible incompatibilities.
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
// Blank out some of the outputs
if ((nHashType & 0x1f) == SIGHASH_NONE)
{
// Wildcard payee
txTmp.vout.clear();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
// Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
printf("ERROR: SignatureHash(): nOut=%d out of range\n", nOut);
return one;
}
txTmp.vout.resize(nOut+1);
for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
// Blank out other inputs completely, not recommended for open transactions
if (nHashType & SIGHASH_ANYONECANPAY)
{
txTmp.vin[0] = txTmp.vin[nIn];
txTmp.vin.resize(1);
}
// Serialize and hash
CHashWriter ss(SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS);
ss << txTmp << nHashType;
return ss.GetHash();
}
void static RandomScript(CScript &script) {
static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
script = CScript();
int ops = (insecure_rand() % 10);
for (int i=0; i<ops; i++)
script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))];
}
void static RandomTransaction(CMutableTransaction &tx, bool fSingle) {
tx.nVersion = insecure_rand();
tx.vin.clear();
tx.vout.clear();
tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;
int ins = (insecure_rand() % 4) + 1;
int outs = fSingle ? ins : (insecure_rand() % 4) + 1;
for (int in = 0; in < ins; in++) {
tx.vin.push_back(CTxIn());
CTxIn &txin = tx.vin.back();
txin.prevout.hash = GetRandHash();
txin.prevout.n = insecure_rand() % 4;
RandomScript(txin.scriptSig);
txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;
}
for (int out = 0; out < outs; out++) {
tx.vout.push_back(CTxOut());
CTxOut &txout = tx.vout.back();
txout.nValue = insecure_rand() % 100000000;
RandomScript(txout.scriptPubKey);
}
}
BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(sighash_test)
{
seed_insecure_rand(false);
#if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n";
std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
#endif
int nRandomTests = 50000;
#if defined(PRINT_SIGHASH_JSON)
nRandomTests = 500;
#endif
for (int i=0; i<nRandomTests; i++) {
int nHashType = insecure_rand();
CMutableTransaction txTo;
RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
CScript scriptCode;
RandomScript(scriptCode);
int nIn = insecure_rand() % txTo.vin.size();
uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);
sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SIGVERSION_BASE);
#if defined(PRINT_SIGHASH_JSON)
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << txTo;
std::cout << "\t[\"" ;
std::cout << HexStr(ss.begin(), ss.end()) << "\", \"";
std::cout << HexStr(scriptCode) << "\", ";
std::cout << nIn << ", ";
std::cout << nHashType << ", \"";
std::cout << sho.GetHex() << "\"]";
if (i+1 != nRandomTests) {
std::cout << ",";
}
std::cout << "\n";
#endif
BOOST_CHECK(sh == sho);
}
#if defined(PRINT_SIGHASH_JSON)
std::cout << "]\n";
#endif
}
// Goal: check that SignatureHash generates correct hash
BOOST_AUTO_TEST_CASE(sighash_from_data)
{
UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
std::string strTest = test.write();
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
if (test.size() == 1) continue; // comment
std::string raw_tx, raw_script, sigHashHex;
int nIn, nHashType;
uint256 sh;
CTransactionRef tx;
CScript scriptCode = CScript();
try {
// deserialize test data
raw_tx = test[0].get_str();
raw_script = test[1].get_str();
nIn = test[2].get_int();
nHashType = test[3].get_int();
sigHashHex = test[4].get_str();
CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);
stream >> tx;
CValidationState state;
BOOST_CHECK_MESSAGE(CheckTransaction(*tx, state), strTest);
BOOST_CHECK(state.IsValid());
std::vector<unsigned char> raw = ParseHex(raw_script);
scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
} catch (...) {
BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
continue;
}
sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SIGVERSION_BASE);
BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
| bluecoiner/bluecoin-new | src/test/sighash_tests.cpp | C++ | mit | 7,209 |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace log4net.Core
{
/// <summary>
/// Implementation of the <see cref="ILoggerWrapper"/> interface.
/// </summary>
/// <remarks>
/// <para>
/// This class should be used as the base for all wrapper implementations.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public abstract class LoggerWrapperImpl : ILoggerWrapper
{
#region Protected Instance Constructors
/// <summary>
/// Constructs a new wrapper for the specified logger.
/// </summary>
/// <param name="logger">The logger to wrap.</param>
/// <remarks>
/// <para>
/// Constructs a new wrapper for the specified logger.
/// </para>
/// </remarks>
protected LoggerWrapperImpl(ILogger logger)
{
m_logger = logger;
}
#endregion Public Instance Constructors
#region Implementation of ILoggerWrapper
/// <summary>
/// Gets the implementation behind this wrapper object.
/// </summary>
/// <value>
/// The <see cref="ILogger"/> object that this object is implementing.
/// </value>
/// <remarks>
/// <para>
/// The <c>Logger</c> object may not be the same object as this object
/// because of logger decorators.
/// </para>
/// <para>
/// This gets the actual underlying objects that is used to process
/// the log events.
/// </para>
/// </remarks>
virtual public ILogger Logger
{
get { return m_logger; }
}
#endregion
#region Private Instance Fields
/// <summary>
/// The logger that this object is wrapping
/// </summary>
private readonly ILogger m_logger;
#endregion Private Instance Fields
}
}
| red2901/sandbox | exceldna/Libs/log4net-1.2.13/src/Core/LoggerWrapperImpl.cs | C# | mit | 2,451 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Specialized;
using System.Text;
namespace System.Configuration
{
public sealed class CommaDelimitedStringCollection : StringCollection
{
private bool _modified;
private string _originalString;
public CommaDelimitedStringCollection()
{
IsReadOnly = false;
_modified = false;
_originalString = ToString();
}
public bool IsModified => _modified || (ToString() != _originalString);
public new bool IsReadOnly { get; private set; }
public new string this[int index]
{
get { return base[index]; }
set
{
ThrowIfReadOnly();
ThrowIfContainsDelimiter(value);
_modified = true;
base[index] = value.Trim();
}
}
internal void FromString(string list)
{
char[] delimiters = { ',' };
if (list != null)
{
string[] items = list.Split(delimiters);
foreach (string item in items)
{
string trimmedItem = item.Trim();
if (trimmedItem.Length != 0) Add(item.Trim());
}
}
_originalString = ToString();
IsReadOnly = false;
_modified = false;
}
public override string ToString()
{
if (Count <= 0) return null;
StringBuilder sb = new StringBuilder();
foreach (string str in this)
{
ThrowIfContainsDelimiter(str);
// Since the add methods are not virtual they could still add bad data
// by casting the collection to a string collection. This check will catch
// it before serialization, late is better than never.
sb.Append(str.Trim());
sb.Append(',');
}
if (sb.Length > 0) sb.Length = sb.Length - 1;
return sb.Length == 0 ? null : sb.ToString();
}
private void ThrowIfReadOnly()
{
if (IsReadOnly) throw new ConfigurationErrorsException(SR.Config_base_read_only);
}
private static void ThrowIfContainsDelimiter(string value)
{
if (value.Contains(",")) // string.Contains(char) is .NetCore2.1+ specific
throw new ConfigurationErrorsException(SR.Format(SR.Config_base_value_cannot_contain, ","));
}
public void SetReadOnly()
{
IsReadOnly = true;
}
public new void Add(string value)
{
ThrowIfReadOnly();
ThrowIfContainsDelimiter(value);
_modified = true;
base.Add(value.Trim());
}
public new void AddRange(string[] range)
{
ThrowIfReadOnly();
_modified = true;
foreach (string str in range)
{
ThrowIfContainsDelimiter(str);
base.Add(str.Trim());
}
}
public new void Clear()
{
ThrowIfReadOnly();
_modified = true;
base.Clear();
}
public new void Insert(int index, string value)
{
ThrowIfReadOnly();
ThrowIfContainsDelimiter(value);
_modified = true;
base.Insert(index, value.Trim());
}
public new void Remove(string value)
{
ThrowIfReadOnly();
ThrowIfContainsDelimiter(value);
_modified = true;
base.Remove(value.Trim());
}
public CommaDelimitedStringCollection Clone()
{
CommaDelimitedStringCollection copy = new CommaDelimitedStringCollection();
// Copy all values
foreach (string str in this) copy.Add(str);
// Copy Attributes
copy._modified = false;
copy.IsReadOnly = IsReadOnly;
copy._originalString = _originalString;
return copy;
}
}
}
| ptoonen/corefx | src/System.Configuration.ConfigurationManager/src/System/Configuration/StringAttributeCollection.cs | C# | mit | 4,354 |
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\Persistence;
/**
* Contract for a Doctrine persistence layer ObjectManager class to implement.
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.org
* @since 2.1
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Jonathan Wage <jonwage@gmail.com>
*/
interface ObjectManager
{
/**
* Finds a object by its identifier.
*
* This is just a convenient shortcut for getRepository($className)->find($id).
*
* @param string
* @param mixed
* @return object
*/
public function find($className, $id);
/**
* Tells the ObjectManager to make an instance managed and persistent.
*
* The object will be entered into the database as a result of the flush operation.
*
* NOTE: The persist operation always considers objects that are not yet known to
* this ObjectManager as NEW. Do not pass detached objects to the persist operation.
*
* @param object $object The instance to make managed and persistent.
*/
public function persist($object);
/**
* Removes an object instance.
*
* A removed object will be removed from the database as a result of the flush operation.
*
* @param object $object The object instance to remove.
*/
public function remove($object);
/**
* Merges the state of a detached object into the persistence context
* of this ObjectManager and returns the managed copy of the object.
* The object passed to merge will not become associated/managed with this ObjectManager.
*
* @param object $object
*/
public function merge($object);
/**
* Detaches an object from the ObjectManager, causing a managed object to
* become detached. Unflushed changes made to the object if any
* (including removal of the object), will not be synchronized to the database.
* Objects which previously referenced the detached object will continue to
* reference it.
*
* @param object $object The object to detach.
*/
public function detach($object);
/**
* Refreshes the persistent state of an object from the database,
* overriding any local changes that have not yet been persisted.
*
* @param object $object The object to refresh.
*/
public function refresh($object);
/**
* Flushes all changes to objects that have been queued up to now to the database.
* This effectively synchronizes the in-memory state of managed objects with the
* database.
*/
public function flush();
/**
* Gets the repository for a class.
*
* @param string $className
* @return \Doctrine\Common\Persistence\ObjectRepository
*/
public function getRepository($className);
/**
* Returns the ClassMetadata descriptor for a class.
*
* The class name must be the fully-qualified class name without a leading backslash
* (as it is returned by get_class($obj)).
*
* @param string $className
* @return \Doctrine\Common\Persistence\Mapping\ClassMetadata
*/
public function getClassMetadata($className);
/**
* Gets the metadata factory used to gather the metadata of classes.
*
* @return Doctrine\Common\Persistence\Mapping\ClassMetadataFactory
*/
public function getMetadataFactory();
} | cristi23/WIDE | vendor/doctrine-common/lib/Doctrine/Common/Persistence/ObjectManager.php | PHP | mit | 4,414 |
/*! gridster.js - v0.5.3 - 2014-07-04 - * http://gridster.net/ - Copyright (c) 2014 ducksboard; Licensed MIT */ (function(t,i){"function"==typeof define&&define.amd?define("gridster-coords",["jquery"],i):t.GridsterCoords=i(t.$||t.jQuery)})(this,function(t){function i(i){return i[0]&&t.isPlainObject(i[0])?this.data=i[0]:this.el=i,this.isCoords=!0,this.coords={},this.init(),this}var e=i.prototype;return e.init=function(){this.set(),this.original_coords=this.get()},e.set=function(t,i){var e=this.el;if(e&&!t&&(this.data=e.offset(),this.data.width=e.width(),this.data.height=e.height()),e&&t&&!i){var s=e.offset();this.data.top=s.top,this.data.left=s.left}var r=this.data;return r.left===void 0&&(r.left=r.x1),r.top===void 0&&(r.top=r.y1),this.coords.x1=r.left,this.coords.y1=r.top,this.coords.x2=r.left+r.width,this.coords.y2=r.top+r.height,this.coords.cx=r.left+r.width/2,this.coords.cy=r.top+r.height/2,this.coords.width=r.width,this.coords.height=r.height,this.coords.el=e||!1,this},e.update=function(i){if(!i&&!this.el)return this;if(i){var e=t.extend({},this.data,i);return this.data=e,this.set(!0,!0)}return this.set(!0),this},e.get=function(){return this.coords},e.destroy=function(){this.el.removeData("coords"),delete this.el},t.fn.coords=function(){if(this.data("coords"))return this.data("coords");var t=new i(this,arguments[0]);return this.data("coords",t),t},i}),function(t,i){"function"==typeof define&&define.amd?define("gridster-collision",["jquery","gridster-coords"],i):t.GridsterCollision=i(t.$||t.jQuery,t.GridsterCoords)}(this,function(t){function i(i,s,r){this.options=t.extend(e,r),this.$element=i,this.last_colliders=[],this.last_colliders_coords=[],this.set_colliders(s),this.init()}var e={colliders_context:document.body,overlapping_region:"C"};i.defaults=e;var s=i.prototype;return s.init=function(){this.find_collisions()},s.overlaps=function(t,i){var e=!1,s=!1;return(i.x1>=t.x1&&i.x1<=t.x2||i.x2>=t.x1&&i.x2<=t.x2||t.x1>=i.x1&&t.x2<=i.x2)&&(e=!0),(i.y1>=t.y1&&i.y1<=t.y2||i.y2>=t.y1&&i.y2<=t.y2||t.y1>=i.y1&&t.y2<=i.y2)&&(s=!0),e&&s},s.detect_overlapping_region=function(t,i){var e="",s="";return t.y1>i.cy&&t.y1<i.y2&&(e="N"),t.y2>i.y1&&t.y2<i.cy&&(e="S"),t.x1>i.cx&&t.x1<i.x2&&(s="W"),t.x2>i.x1&&t.x2<i.cx&&(s="E"),e+s||"C"},s.calculate_overlapped_area_coords=function(i,e){var s=Math.max(i.x1,e.x1),r=Math.max(i.y1,e.y1),o=Math.min(i.x2,e.x2),a=Math.min(i.y2,e.y2);return t({left:s,top:r,width:o-s,height:a-r}).coords().get()},s.calculate_overlapped_area=function(t){return t.width*t.height},s.manage_colliders_start_stop=function(i,e,s){for(var r=this.last_colliders_coords,o=0,a=r.length;a>o;o++)-1===t.inArray(r[o],i)&&e.call(this,r[o]);for(var n=0,h=i.length;h>n;n++)-1===t.inArray(i[n],r)&&s.call(this,i[n])},s.find_collisions=function(i){for(var e=this,s=this.options.overlapping_region,r=[],o=[],a=this.colliders||this.$colliders,n=a.length,h=e.$element.coords().update(i||!1).get();n--;){var _=e.$colliders?t(a[n]):a[n],d=_.isCoords?_:_.coords(),l=d.get(),c=e.overlaps(h,l);if(c){var g=e.detect_overlapping_region(h,l);if(g===s||"all"===s){var p=e.calculate_overlapped_area_coords(h,l),u=e.calculate_overlapped_area(p),f={area:u,area_coords:p,region:g,coords:l,player_coords:h,el:_};e.options.on_overlap&&e.options.on_overlap.call(this,f),r.push(d),o.push(f)}}}return(e.options.on_overlap_stop||e.options.on_overlap_start)&&this.manage_colliders_start_stop(r,e.options.on_overlap_start,e.options.on_overlap_stop),this.last_colliders_coords=r,o},s.get_closest_colliders=function(t){var i=this.find_collisions(t);return i.sort(function(t,i){return"C"===t.region&&"C"===i.region?t.coords.y1<i.coords.y1||t.coords.x1<i.coords.x1?-1:1:t.area<i.area?1:1}),i},s.set_colliders=function(i){"string"==typeof i||i instanceof t?this.$colliders=t(i,this.options.colliders_context).not(this.$element):this.colliders=t(i)},t.fn.collision=function(t,e){return new i(this,t,e)},i}),function(t){t.delay=function(t,i){var e=Array.prototype.slice.call(arguments,2);return setTimeout(function(){return t.apply(null,e)},i)},t.debounce=function(t,i,e){var s;return function(){var r=this,o=arguments,a=function(){s=null,e||t.apply(r,o)};e&&!s&&t.apply(r,o),clearTimeout(s),s=setTimeout(a,i)}},t.throttle=function(t,i){var e,s,r,o,a,n,h=debounce(function(){a=o=!1},i);return function(){e=this,s=arguments;var _=function(){r=null,a&&t.apply(e,s),h()};return r||(r=setTimeout(_,i)),o?a=!0:n=t.apply(e,s),h(),o=!0,n}}}(window),function(t,i){"function"==typeof define&&define.amd?define("gridster-draggable",["jquery"],i):t.GridsterDraggable=i(t.$||t.jQuery)}(this,function(t){function i(i,s){this.options=t.extend({},e,s),this.$document=t(document),this.$container=t(i),this.$dragitems=t(this.options.items,this.$container),this.is_dragging=!1,this.player_min_left=0+this.options.offset_left,this.init()}var e={items:"li",distance:1,limit:!0,offset_left:0,autoscroll:!0,ignore_dragging:["INPUT","TEXTAREA","SELECT","BUTTON"],handle:null,container_width:0,move_element:!0,helper:!1,remove_helper:!0},s=t(window),r={x:"left",y:"top"},o=!!("ontouchstart"in window),a={start:"touchstart.gridster-draggable mousedown.gridster-draggable",move:"touchmove.gridster-draggable mousemove.gridster-draggable",end:"touchend.gridster-draggable mouseup.gridster-draggable"},n=function(t){return t.charAt(0).toUpperCase()+t.slice(1)};i.defaults=e;var h=i.prototype;return h.init=function(){var i=this.$container.css("position");this.calculate_dimensions(),this.$container.css("position","static"===i?"relative":i),this.disabled=!1,this.events(),t(window).bind("resize.gridster-draggable",throttle(t.proxy(this.calculate_dimensions,this),200))},h.events=function(){this.$container.on("selectstart.gridster-draggable",t.proxy(this.on_select_start,this)),this.$container.on(a.start,this.options.items,t.proxy(this.drag_handler,this)),this.$document.on(a.end,t.proxy(function(t){this.is_dragging=!1,this.disabled||(this.$document.off(a.move),this.drag_start&&this.on_dragstop(t))},this))},h.get_actual_pos=function(t){var i=t.position();return i},h.get_mouse_pos=function(t){if(t.originalEvent&&t.originalEvent.touches){var i=t.originalEvent;t=i.touches.length?i.touches[0]:i.changedTouches[0]}return{left:t.clientX,top:t.clientY}},h.get_offset=function(i){i.preventDefault();var e=this.get_mouse_pos(i),s=Math.round(e.left-this.mouse_init_pos.left),r=Math.round(e.top-this.mouse_init_pos.top),o=Math.round(this.el_init_offset.left+s-this.baseX+t(window).scrollLeft()-this.win_offset_x),a=Math.round(this.el_init_offset.top+r-this.baseY+t(window).scrollTop()-this.win_offset_y);return this.options.limit&&(o>this.player_max_left?o=this.player_max_left:this.player_min_left>o&&(o=this.player_min_left)),{position:{left:o,top:a},pointer:{left:e.left,top:e.top,diff_left:s+(t(window).scrollLeft()-this.win_offset_x),diff_top:r+(t(window).scrollTop()-this.win_offset_y)}}},h.get_drag_data=function(t){var i=this.get_offset(t);return i.$player=this.$player,i.$helper=this.helper?this.$helper:this.$player,i},h.set_limits=function(t){return t||(t=this.$container.width()),this.player_max_left=t-this.player_width+-this.options.offset_left,this.options.container_width=t,this},h.scroll_in=function(i,e){var o,a=r[i],h=50,_=30,d="x"===i,l=d?this.window_width:this.window_height,c=d?t(document).width():t(document).height(),g=d?this.$player.width():this.$player.height(),p=s["scroll"+n(a)](),u=p,f=u+l,w=f-h,m=u+h,y=u+e.pointer[a],v=c-l+g;return y>=w&&(o=p+_,v>o&&(s["scroll"+n(a)](o),this["scroll_offset_"+i]+=_)),m>=y&&(o=p-_,o>0&&(s["scroll"+n(a)](o),this["scroll_offset_"+i]-=_)),this},h.manage_scroll=function(t){this.scroll_in("x",t),this.scroll_in("y",t)},h.calculate_dimensions=function(){this.window_height=s.height(),this.window_width=s.width()},h.drag_handler=function(i){if(i.target.nodeName,!this.disabled&&(1===i.which||o)&&!this.ignore_drag(i)){var e=this,s=!0;return this.$player=t(i.currentTarget),this.el_init_pos=this.get_actual_pos(this.$player),this.mouse_init_pos=this.get_mouse_pos(i),this.offsetY=this.mouse_init_pos.top-this.el_init_pos.top,this.$document.on(a.move,function(t){var i=e.get_mouse_pos(t),r=Math.abs(i.left-e.mouse_init_pos.left),o=Math.abs(i.top-e.mouse_init_pos.top);return r>e.options.distance||o>e.options.distance?s?(s=!1,e.on_dragstart.call(e,t),!1):(e.is_dragging===!0&&e.on_dragmove.call(e,t),!1):!1}),o?void 0:!1}},h.on_dragstart=function(i){if(i.preventDefault(),this.is_dragging)return this;this.drag_start=this.is_dragging=!0;var e=this.$container.offset();return this.baseX=Math.round(e.left),this.baseY=Math.round(e.top),this.initial_container_width=this.options.container_width||this.$container.width(),"clone"===this.options.helper?(this.$helper=this.$player.clone().appendTo(this.$container).addClass("helper"),this.helper=!0):this.helper=!1,this.win_offset_y=t(window).scrollTop(),this.win_offset_x=t(window).scrollLeft(),this.scroll_offset_y=0,this.scroll_offset_x=0,this.el_init_offset=this.$player.offset(),this.player_width=this.$player.width(),this.player_height=this.$player.height(),this.set_limits(this.options.container_width),this.options.start&&this.options.start.call(this.$player,i,this.get_drag_data(i)),!1},h.on_dragmove=function(t){var i=this.get_drag_data(t);this.options.autoscroll&&this.manage_scroll(i),this.options.move_element&&(this.helper?this.$helper:this.$player).css({position:"absolute",left:i.position.left,top:i.position.top});var e=this.last_position||i.position;return i.prev_position=e,this.options.drag&&this.options.drag.call(this.$player,t,i),this.last_position=i.position,!1},h.on_dragstop=function(t){var i=this.get_drag_data(t);return this.drag_start=!1,this.options.stop&&this.options.stop.call(this.$player,t,i),this.helper&&this.options.remove_helper&&this.$helper.remove(),!1},h.on_select_start=function(t){return this.disabled||this.ignore_drag(t)?void 0:!1},h.enable=function(){this.disabled=!1},h.disable=function(){this.disabled=!0},h.destroy=function(){this.disable(),this.$container.off(".gridster-draggable"),this.$document.off(".gridster-draggable"),t(window).off(".gridster-draggable"),t.removeData(this.$container,"drag")},h.ignore_drag=function(i){return this.options.handle?!t(i.target).is(this.options.handle):t.isFunction(this.options.ignore_dragging)?this.options.ignore_dragging(i):t(i.target).is(this.options.ignore_dragging.join(", "))},t.fn.drag=function(t){return new i(this,t)},i}),function(t,i){"function"==typeof define&&define.amd?define(["jquery","gridster-draggable","gridster-collision"],i):t.Gridster=i(t.$||t.jQuery,t.GridsterDraggable,t.GridsterCollision)}(this,function(t,i){function e(i,e){this.options=t.extend(!0,{},s,e),this.$el=t(i),this.$wrapper=this.$el.parent(),this.$widgets=this.$el.children(this.options.widget_selector).addClass("gs-w"),this.widgets=[],this.$changed=t([]),this.wrapper_width=this.$wrapper.width(),this.min_widget_width=2*this.options.widget_margins[0]+this.options.widget_base_dimensions[0],this.min_widget_height=2*this.options.widget_margins[1]+this.options.widget_base_dimensions[1],this.generated_stylesheets=[],this.$style_tags=t([]),this.options.auto_init&&this.init()}var s={namespace:"",widget_selector:"li",widget_margins:[10,10],widget_base_dimensions:[400,225],extra_rows:0,extra_cols:0,min_cols:1,max_cols:1/0,min_rows:15,max_size_x:!1,autogrow_cols:!1,autogenerate_stylesheet:!0,avoid_overlapped_widgets:!0,auto_init:!0,serialize_params:function(t,i){return{col:i.col,row:i.row,size_x:i.size_x,size_y:i.size_y}},collision:{},draggable:{items:".gs-w",distance:4,ignore_dragging:i.defaults.ignore_dragging.slice(0)},resize:{enabled:!1,axes:["both"],handle_append_to:"",handle_class:"gs-resize-handle",max_size:[1/0,1/0],min_size:[1,1]}};e.defaults=s,e.generated_stylesheets=[],e.sort_by_row_asc=function(i){return i=i.sort(function(i,e){return i.row||(i=t(i).coords().grid,e=t(e).coords().grid),i.row>e.row?1:-1})},e.sort_by_row_and_col_asc=function(t){return t=t.sort(function(t,i){return t.row>i.row||t.row===i.row&&t.col>i.col?1:-1})},e.sort_by_col_asc=function(t){return t=t.sort(function(t,i){return t.col>i.col?1:-1})},e.sort_by_row_desc=function(t){return t=t.sort(function(t,i){return t.row+t.size_y<i.row+i.size_y?1:-1})};var r=e.prototype;return r.init=function(){this.options.resize.enabled&&this.setup_resize(),this.generate_grid_and_stylesheet(),this.get_widgets_from_DOM(),this.set_dom_grid_height(),this.set_dom_grid_width(),this.$wrapper.addClass("ready"),this.draggable(),this.options.resize.enabled&&this.resizable(),t(window).bind("resize.gridster",throttle(t.proxy(this.recalculate_faux_grid,this),200))},r.disable=function(){return this.$wrapper.find(".player-revert").removeClass("player-revert"),this.drag_api.disable(),this},r.enable=function(){return this.drag_api.enable(),this},r.disable_resize=function(){return this.$el.addClass("gs-resize-disabled"),this.resize_api.disable(),this},r.enable_resize=function(){return this.$el.removeClass("gs-resize-disabled"),this.resize_api.enable(),this},r.add_widget=function(i,e,s,r,o,a,n){var h;e||(e=1),s||(s=1),!r&!o?h=this.next_position(e,s):(h={col:r,row:o,size_x:e,size_y:s},this.empty_cells(r,o,e,s));var _=t(i).attr({"data-col":h.col,"data-row":h.row,"data-sizex":e,"data-sizey":s}).addClass("gs-w").appendTo(this.$el).hide();return this.$widgets=this.$widgets.add(_),this.register_widget(_),this.add_faux_rows(h.size_y),a&&this.set_widget_max_size(_,a),n&&this.set_widget_min_size(_,n),this.set_dom_grid_width(),this.set_dom_grid_height(),this.drag_api.set_limits(this.cols*this.min_widget_width),_.fadeIn()},r.set_widget_min_size=function(t,i){if(t="number"==typeof t?this.$widgets.eq(t):t,!t.length)return this;var e=t.data("coords").grid;return e.min_size_x=i[0],e.min_size_y=i[1],this},r.set_widget_max_size=function(t,i){if(t="number"==typeof t?this.$widgets.eq(t):t,!t.length)return this;var e=t.data("coords").grid;return e.max_size_x=i[0],e.max_size_y=i[1],this},r.add_resize_handle=function(i){var e=this.options.resize.handle_append_to;return t(this.resize_handle_tpl).appendTo(e?t(e,i):i),this},r.resize_widget=function(t,i,e,s){var r=t.coords().grid,o=r.col,a=this.options.max_cols,n=r.size_y,h=r.col,_=h;i||(i=r.size_x),e||(e=r.size_y),1/0!==a&&(i=Math.min(i,a-o+1)),e>n&&this.add_faux_rows(Math.max(e-n,0));var d=o+i-1;d>this.cols&&this.add_faux_cols(d-this.cols);var l={col:_,row:r.row,size_x:i,size_y:e};return this.mutate_widget_in_gridmap(t,r,l),this.set_dom_grid_height(),this.set_dom_grid_width(),s&&s.call(this,l.size_x,l.size_y),t},r.mutate_widget_in_gridmap=function(i,e,s){e.size_x;var r=e.size_y,o=this.get_cells_occupied(e),a=this.get_cells_occupied(s),n=[];t.each(o.cols,function(i,e){-1===t.inArray(e,a.cols)&&n.push(e)});var h=[];t.each(a.cols,function(i,e){-1===t.inArray(e,o.cols)&&h.push(e)});var _=[];t.each(o.rows,function(i,e){-1===t.inArray(e,a.rows)&&_.push(e)});var d=[];if(t.each(a.rows,function(i,e){-1===t.inArray(e,o.rows)&&d.push(e)}),this.remove_from_gridmap(e),h.length){var l=[s.col,s.row,s.size_x,Math.min(r,s.size_y),i];this.empty_cells.apply(this,l)}if(d.length){var c=[s.col,s.row,s.size_x,s.size_y,i];this.empty_cells.apply(this,c)}if(e.col=s.col,e.row=s.row,e.size_x=s.size_x,e.size_y=s.size_y,this.add_to_gridmap(s,i),i.removeClass("player-revert"),i.data("coords").update({width:s.size_x*this.options.widget_base_dimensions[0]+2*(s.size_x-1)*this.options.widget_margins[0],height:s.size_y*this.options.widget_base_dimensions[1]+2*(s.size_y-1)*this.options.widget_margins[1]}),i.attr({"data-col":s.col,"data-row":s.row,"data-sizex":s.size_x,"data-sizey":s.size_y}),n.length){var g=[n[0],s.row,n.length,Math.min(r,s.size_y),i];this.remove_empty_cells.apply(this,g)}if(_.length){var p=[s.col,s.row,s.size_x,s.size_y,i];this.remove_empty_cells.apply(this,p)}return this.move_widget_up(i),this},r.empty_cells=function(i,e,s,r,o){var a=this.widgets_below({col:i,row:e-r,size_x:s,size_y:r});return a.not(o).each(t.proxy(function(i,s){var o=t(s).coords().grid;if(e+r-1>=o.row){var a=e+r-o.row;this.move_widget_down(t(s),a)}},this)),this.set_dom_grid_height(),this},r.remove_empty_cells=function(i,e,s,r,o){var a=this.widgets_below({col:i,row:e,size_x:s,size_y:r});return a.not(o).each(t.proxy(function(i,e){this.move_widget_up(t(e),r)},this)),this.set_dom_grid_height(),this},r.next_position=function(t,i){t||(t=1),i||(i=1);for(var s,r=this.gridmap,o=r.length,a=[],n=1;o>n;n++){s=r[n].length;for(var h=1;s>=h;h++){var _=this.can_move_to({size_x:t,size_y:i},n,h);_&&a.push({col:n,row:h,size_y:i,size_x:t})}}return a.length?e.sort_by_row_and_col_asc(a)[0]:!1},r.remove_widget=function(i,e,s){var r=i instanceof t?i:t(i),o=r.coords().grid;t.isFunction(e)&&(s=e,e=!1),this.cells_occupied_by_placeholder={},this.$widgets=this.$widgets.not(r);var a=this.widgets_below(r);return this.remove_from_gridmap(o),r.fadeOut(t.proxy(function(){r.remove(),e||a.each(t.proxy(function(i,e){this.move_widget_up(t(e),o.size_y)},this)),this.set_dom_grid_height(),s&&s.call(this,i)},this)),this},r.remove_all_widgets=function(i){return this.$widgets.each(t.proxy(function(t,e){this.remove_widget(e,!0,i)},this)),this},r.serialize=function(i){return i||(i=this.$widgets),i.map(t.proxy(function(i,e){var s=t(e);return this.options.serialize_params(s,s.coords().grid)},this))},r.serialize_changed=function(){return this.serialize(this.$changed)},r.dom_to_coords=function(t){return{col:parseInt(t.attr("data-col"),10),row:parseInt(t.attr("data-row"),10),size_x:parseInt(t.attr("data-sizex"),10)||1,size_y:parseInt(t.attr("data-sizey"),10)||1,max_size_x:parseInt(t.attr("data-max-sizex"),10)||!1,max_size_y:parseInt(t.attr("data-max-sizey"),10)||!1,min_size_x:parseInt(t.attr("data-min-sizex"),10)||!1,min_size_y:parseInt(t.attr("data-min-sizey"),10)||!1,el:t}},r.register_widget=function(i){var e=i instanceof jQuery,s=e?this.dom_to_coords(i):i;e||(i=s.el);var r=this.can_go_widget_up(s);return r&&(s.row=r,i.attr("data-row",r),this.$el.trigger("gridster:positionchanged",[s])),this.options.avoid_overlapped_widgets&&!this.can_move_to({size_x:s.size_x,size_y:s.size_y},s.col,s.row)&&(t.extend(s,this.next_position(s.size_x,s.size_y)),i.attr({"data-col":s.col,"data-row":s.row,"data-sizex":s.size_x,"data-sizey":s.size_y})),i.data("coords",i.coords()),i.data("coords").grid=s,this.add_to_gridmap(s,i),this.options.resize.enabled&&this.add_resize_handle(i),!!r},r.update_widget_position=function(t,i){return this.for_each_cell_occupied(t,function(t,e){return this.gridmap[t]?(this.gridmap[t][e]=i,void 0):this}),this},r.remove_from_gridmap=function(t){return this.update_widget_position(t,!1)},r.add_to_gridmap=function(i,e){if(this.update_widget_position(i,e||i.el),i.el){var s=this.widgets_below(i.el);s.each(t.proxy(function(i,e){this.move_widget_up(t(e))},this))}},r.draggable=function(){var i=this,e=t.extend(!0,{},this.options.draggable,{offset_left:this.options.widget_margins[0],offset_top:this.options.widget_margins[1],container_width:this.cols*this.min_widget_width,limit:!0,start:function(e,s){i.$widgets.filter(".player-revert").removeClass("player-revert"),i.$player=t(this),i.$helper=t(s.$helper),i.helper=!i.$helper.is(i.$player),i.on_start_drag.call(i,e,s),i.$el.trigger("gridster:dragstart")},stop:function(t,e){i.on_stop_drag.call(i,t,e),i.$el.trigger("gridster:dragstop")},drag:throttle(function(t,e){i.on_drag.call(i,t,e),i.$el.trigger("gridster:drag")},60)});return this.drag_api=this.$el.drag(e),this},r.resizable=function(){return this.resize_api=this.$el.drag({items:"."+this.options.resize.handle_class,offset_left:this.options.widget_margins[0],container_width:this.container_width,move_element:!1,resize:!0,limit:this.options.autogrow_cols?!1:!0,start:t.proxy(this.on_start_resize,this),stop:t.proxy(function(i,e){delay(t.proxy(function(){this.on_stop_resize(i,e)},this),120)},this),drag:throttle(t.proxy(this.on_resize,this),60)}),this},r.setup_resize=function(){this.resize_handle_class=this.options.resize.handle_class;var i=this.options.resize.axes,e='<span class="'+this.resize_handle_class+" "+this.resize_handle_class+'-{type}" />';return this.resize_handle_tpl=t.map(i,function(t){return e.replace("{type}",t)}).join(""),t.isArray(this.options.draggable.ignore_dragging)&&this.options.draggable.ignore_dragging.push("."+this.resize_handle_class),this},r.on_start_drag=function(i,e){this.$helper.add(this.$player).add(this.$wrapper).addClass("dragging"),this.highest_col=this.get_highest_occupied_cell().col,this.$player.addClass("player"),this.player_grid_data=this.$player.coords().grid,this.placeholder_grid_data=t.extend({},this.player_grid_data),this.set_dom_grid_height(this.$el.height()+this.player_grid_data.size_y*this.min_widget_height),this.set_dom_grid_width(this.cols);var s=this.player_grid_data.size_x,r=this.cols-this.highest_col;this.options.autogrow_cols&&s>=r&&this.add_faux_cols(Math.min(s-r,1));var o=this.faux_grid,a=this.$player.data("coords").coords;this.cells_occupied_by_player=this.get_cells_occupied(this.player_grid_data),this.cells_occupied_by_placeholder=this.get_cells_occupied(this.placeholder_grid_data),this.last_cols=[],this.last_rows=[],this.collision_api=this.$helper.collision(o,this.options.collision),this.$preview_holder=t("<"+this.$player.get(0).tagName+" />",{"class":"preview-holder","data-row":this.$player.attr("data-row"),"data-col":this.$player.attr("data-col"),css:{width:a.width,height:a.height}}).appendTo(this.$el),this.options.draggable.start&&this.options.draggable.start.call(this,i,e)},r.on_drag=function(t,i){if(null===this.$player)return!1;var e={left:i.position.left+this.baseX,top:i.position.top+this.baseY};if(this.options.autogrow_cols){var s=this.placeholder_grid_data.col+this.placeholder_grid_data.size_x-1;s>=this.cols-1&&this.options.max_cols>=this.cols+1&&(this.add_faux_cols(1),this.set_dom_grid_width(this.cols+1),this.drag_api.set_limits(this.container_width)),this.collision_api.set_colliders(this.faux_grid)}this.colliders_data=this.collision_api.get_closest_colliders(e),this.on_overlapped_column_change(this.on_start_overlapping_column,this.on_stop_overlapping_column),this.on_overlapped_row_change(this.on_start_overlapping_row,this.on_stop_overlapping_row),this.helper&&this.$player&&this.$player.css({left:i.position.left,top:i.position.top}),this.options.draggable.drag&&this.options.draggable.drag.call(this,t,i)},r.on_stop_drag=function(t,i){this.$helper.add(this.$player).add(this.$wrapper).removeClass("dragging"),i.position.left=i.position.left+this.baseX,i.position.top=i.position.top+this.baseY,this.colliders_data=this.collision_api.get_closest_colliders(i.position),this.on_overlapped_column_change(this.on_start_overlapping_column,this.on_stop_overlapping_column),this.on_overlapped_row_change(this.on_start_overlapping_row,this.on_stop_overlapping_row),this.$player.addClass("player-revert").removeClass("player").attr({"data-col":this.placeholder_grid_data.col,"data-row":this.placeholder_grid_data.row}).css({left:"",top:""}),this.$changed=this.$changed.add(this.$player),this.cells_occupied_by_player=this.get_cells_occupied(this.placeholder_grid_data),this.set_cells_player_occupies(this.placeholder_grid_data.col,this.placeholder_grid_data.row),this.$player.coords().grid.row=this.placeholder_grid_data.row,this.$player.coords().grid.col=this.placeholder_grid_data.col,this.options.draggable.stop&&this.options.draggable.stop.call(this,t,i),this.$preview_holder.remove(),this.$player=null,this.$helper=null,this.placeholder_grid_data={},this.player_grid_data={},this.cells_occupied_by_placeholder={},this.cells_occupied_by_player={},this.set_dom_grid_height(),this.set_dom_grid_width(),this.options.autogrow_cols&&this.drag_api.set_limits(this.cols*this.min_widget_width)},r.on_start_resize=function(i,e){this.$resized_widget=e.$player.closest(".gs-w"),this.resize_coords=this.$resized_widget.coords(),this.resize_wgd=this.resize_coords.grid,this.resize_initial_width=this.resize_coords.coords.width,this.resize_initial_height=this.resize_coords.coords.height,this.resize_initial_sizex=this.resize_coords.grid.size_x,this.resize_initial_sizey=this.resize_coords.grid.size_y,this.resize_initial_col=this.resize_coords.grid.col,this.resize_last_sizex=this.resize_initial_sizex,this.resize_last_sizey=this.resize_initial_sizey,this.resize_max_size_x=Math.min(this.resize_wgd.max_size_x||this.options.resize.max_size[0],this.options.max_cols-this.resize_initial_col+1),this.resize_max_size_y=this.resize_wgd.max_size_y||this.options.resize.max_size[1],this.resize_min_size_x=this.resize_wgd.min_size_x||this.options.resize.min_size[0]||1,this.resize_min_size_y=this.resize_wgd.min_size_y||this.options.resize.min_size[1]||1,this.resize_initial_last_col=this.get_highest_occupied_cell().col,this.set_dom_grid_width(this.cols),this.resize_dir={right:e.$player.is("."+this.resize_handle_class+"-x"),bottom:e.$player.is("."+this.resize_handle_class+"-y")},this.$resized_widget.css({"min-width":this.options.widget_base_dimensions[0],"min-height":this.options.widget_base_dimensions[1]});var s=this.$resized_widget.get(0).tagName;this.$resize_preview_holder=t("<"+s+" />",{"class":"preview-holder resize-preview-holder","data-row":this.$resized_widget.attr("data-row"),"data-col":this.$resized_widget.attr("data-col"),css:{width:this.resize_initial_width,height:this.resize_initial_height}}).appendTo(this.$el),this.$resized_widget.addClass("resizing"),this.options.resize.start&&this.options.resize.start.call(this,i,e,this.$resized_widget),this.$el.trigger("gridster:resizestart")},r.on_stop_resize=function(i,e){this.$resized_widget.removeClass("resizing").css({width:"",height:""}),delay(t.proxy(function(){this.$resize_preview_holder.remove().css({"min-width":"","min-height":""}),this.options.resize.stop&&this.options.resize.stop.call(this,i,e,this.$resized_widget),this.$el.trigger("gridster:resizestop")},this),300),this.set_dom_grid_width(),this.options.autogrow_cols&&this.drag_api.set_limits(this.cols*this.min_widget_width)},r.on_resize=function(t,i){var e,s=i.pointer.diff_left,r=i.pointer.diff_top,o=this.options.widget_base_dimensions[0],a=this.options.widget_base_dimensions[1],n=this.options.widget_margins[0],h=this.options.widget_margins[1],_=this.resize_max_size_x,d=this.resize_min_size_x,l=this.resize_max_size_y,c=this.resize_min_size_y,g=this.options.autogrow_cols,p=1/0,u=1/0,f=Math.ceil(s/(o+2*n)-.2),w=Math.ceil(r/(a+2*h)-.2),m=Math.max(1,this.resize_initial_sizex+f),y=Math.max(1,this.resize_initial_sizey+w),v=this.container_width/this.min_widget_width-this.resize_initial_col+1,z=v*this.min_widget_width-2*n;if(m=Math.max(Math.min(m,_),d),m=Math.min(v,m),e=_*o+2*(m-1)*n,p=Math.min(e,z),min_width=d*o+2*(m-1)*n,y=Math.max(Math.min(y,l),c),u=l*a+2*(y-1)*h,min_height=c*a+2*(y-1)*h,this.resize_dir.right?y=this.resize_initial_sizey:this.resize_dir.bottom&&(m=this.resize_initial_sizex),g){var x=this.resize_initial_col+m-1;g&&x>=this.resize_initial_last_col&&(this.set_dom_grid_width(Math.max(x+1,this.cols)),x>this.cols&&this.add_faux_cols(x-this.cols))}var $={};!this.resize_dir.bottom&&($.width=Math.max(Math.min(this.resize_initial_width+s,p),min_width)),!this.resize_dir.right&&($.height=Math.max(Math.min(this.resize_initial_height+r,u),min_height)),this.$resized_widget.css($),(m!==this.resize_last_sizex||y!==this.resize_last_sizey)&&(this.resize_widget(this.$resized_widget,m,y),this.set_dom_grid_width(this.cols),this.$resize_preview_holder.css({width:"",height:""}).attr({"data-row":this.$resized_widget.attr("data-row"),"data-sizex":m,"data-sizey":y})),this.options.resize.resize&&this.options.resize.resize.call(this,t,i,this.$resized_widget),this.$el.trigger("gridster:resize"),this.resize_last_sizex=m,this.resize_last_sizey=y},r.on_overlapped_column_change=function(i,e){if(!this.colliders_data.length)return this;var s,r=this.get_targeted_columns(this.colliders_data[0].el.data.col),o=this.last_cols.length,a=r.length;for(s=0;a>s;s++)-1===t.inArray(r[s],this.last_cols)&&(i||t.noop).call(this,r[s]);for(s=0;o>s;s++)-1===t.inArray(this.last_cols[s],r)&&(e||t.noop).call(this,this.last_cols[s]);return this.last_cols=r,this},r.on_overlapped_row_change=function(i,e){if(!this.colliders_data.length)return this;var s,r=this.get_targeted_rows(this.colliders_data[0].el.data.row),o=this.last_rows.length,a=r.length;for(s=0;a>s;s++)-1===t.inArray(r[s],this.last_rows)&&(i||t.noop).call(this,r[s]);for(s=0;o>s;s++)-1===t.inArray(this.last_rows[s],r)&&(e||t.noop).call(this,this.last_rows[s]);this.last_rows=r},r.set_player=function(t,i,e){var s=this;e||this.empty_cells_player_occupies();var r=e?{col:t}:s.colliders_data[0].el.data,o=r.col,a=i||r.row;this.player_grid_data={col:o,row:a,size_y:this.player_grid_data.size_y,size_x:this.player_grid_data.size_x},this.cells_occupied_by_player=this.get_cells_occupied(this.player_grid_data);var n=this.get_widgets_overlapped(this.player_grid_data),h=this.widgets_constraints(n);if(this.manage_movements(h.can_go_up,o,a),this.manage_movements(h.can_not_go_up,o,a),!n.length){var _=this.can_go_player_up(this.player_grid_data);_!==!1&&(a=_),this.set_placeholder(o,a)}return{col:o,row:a}},r.widgets_constraints=function(i){var s,r=t([]),o=[],a=[];return i.each(t.proxy(function(i,e){var s=t(e),n=s.coords().grid;this.can_go_widget_up(n)?(r=r.add(s),o.push(n)):a.push(n)},this)),s=i.not(r),{can_go_up:e.sort_by_row_asc(o),can_not_go_up:e.sort_by_row_desc(a)}},r.manage_movements=function(i,e,s){return t.each(i,t.proxy(function(t,i){var r=i,o=r.el,a=this.can_go_widget_up(r);if(a)this.move_widget_to(o,a),this.set_placeholder(e,a+r.size_y);else{var n=this.can_go_player_up(this.player_grid_data);if(!n){var h=s+this.player_grid_data.size_y-r.row;this.move_widget_down(o,h),this.set_placeholder(e,s)}}},this)),this},r.is_player=function(t,i){if(i&&!this.gridmap[t])return!1;var e=i?this.gridmap[t][i]:t;return e&&(e.is(this.$player)||e.is(this.$helper))},r.is_player_in=function(i,e){var s=this.cells_occupied_by_player||{};return t.inArray(i,s.cols)>=0&&t.inArray(e,s.rows)>=0},r.is_placeholder_in=function(i,e){var s=this.cells_occupied_by_placeholder||{};return this.is_placeholder_in_col(i)&&t.inArray(e,s.rows)>=0},r.is_placeholder_in_col=function(i){var e=this.cells_occupied_by_placeholder||[];return t.inArray(i,e.cols)>=0},r.is_empty=function(t,i){return this.gridmap[t]!==void 0?this.gridmap[t][i]!==void 0&&this.gridmap[t][i]===!1?!0:!1:!0},r.is_occupied=function(t,i){return this.gridmap[t]?this.gridmap[t][i]?!0:!1:!1},r.is_widget=function(t,i){var e=this.gridmap[t];return e?(e=e[i],e?e:!1):!1},r.is_widget_under_player=function(t,i){return this.is_widget(t,i)?this.is_player_in(t,i):!1},r.get_widgets_under_player=function(i){i||(i=this.cells_occupied_by_player||{cols:[],rows:[]});var e=t([]);return t.each(i.cols,t.proxy(function(s,r){t.each(i.rows,t.proxy(function(t,i){this.is_widget(r,i)&&(e=e.add(this.gridmap[r][i]))},this))},this)),e},r.set_placeholder=function(i,e){var s=t.extend({},this.placeholder_grid_data),r=this.widgets_below({col:s.col,row:s.row,size_y:s.size_y,size_x:s.size_x}),o=i+s.size_x-1;o>this.cols&&(i-=o-i);var a=e>this.placeholder_grid_data.row,n=this.placeholder_grid_data.col!==i;this.placeholder_grid_data.col=i,this.placeholder_grid_data.row=e,this.cells_occupied_by_placeholder=this.get_cells_occupied(this.placeholder_grid_data),this.$preview_holder.attr({"data-row":e,"data-col":i}),(a||n)&&r.each(t.proxy(function(e,r){this.move_widget_up(t(r),this.placeholder_grid_data.col-i+s.size_y)},this));var h=this.get_widgets_under_player(this.cells_occupied_by_placeholder);h.length&&h.each(t.proxy(function(i,r){var o=t(r);this.move_widget_down(o,e+s.size_y-o.data("coords").grid.row)},this))},r.can_go_player_up=function(t){var i=t.row+t.size_y-1,e=!0,s=[],r=1e4,o=this.get_widgets_under_player();return this.for_each_column_occupied(t,function(t){var a=this.gridmap[t],n=i+1;for(s[t]=[];--n>0&&(this.is_empty(t,n)||this.is_player(t,n)||this.is_widget(t,n)&&a[n].is(o));)s[t].push(n),r=r>n?n:r;return 0===s[t].length?(e=!1,!0):(s[t].sort(function(t,i){return t-i}),void 0)}),e?this.get_valid_rows(t,s,r):!1},r.can_go_widget_up=function(t){var i=t.row+t.size_y-1,e=!0,s=[],r=1e4;return this.for_each_column_occupied(t,function(o){var a=this.gridmap[o];
s[o]=[];for(var n=i+1;--n>0&&(!this.is_widget(o,n)||this.is_player_in(o,n)||a[n].is(t.el));)this.is_player(o,n)||this.is_placeholder_in(o,n)||this.is_player_in(o,n)||s[o].push(n),r>n&&(r=n);return 0===s[o].length?(e=!1,!0):(s[o].sort(function(t,i){return t-i}),void 0)}),e?this.get_valid_rows(t,s,r):!1},r.get_valid_rows=function(i,e,s){for(var r=i.row,o=i.row+i.size_y-1,a=i.size_y,n=s-1,h=[];o>=++n;){var _=!0;if(t.each(e,function(i,e){t.isArray(e)&&-1===t.inArray(n,e)&&(_=!1)}),_===!0&&(h.push(n),h.length===a))break}var d=!1;return 1===a?h[0]!==r&&(d=h[0]||!1):h[0]!==r&&(d=this.get_consecutive_numbers_index(h,a)),d},r.get_consecutive_numbers_index=function(t,i){for(var e=t.length,s=[],r=!0,o=-1,a=0;e>a;a++){if(r||t[a]===o+1){if(s.push(a),s.length===i)break;r=!1}else s=[],r=!0;o=t[a]}return s.length>=i?t[s[0]]:!1},r.get_widgets_overlapped=function(){var i=t([]),e=[],s=this.cells_occupied_by_player.rows.slice(0);return s.reverse(),t.each(this.cells_occupied_by_player.cols,t.proxy(function(r,o){t.each(s,t.proxy(function(s,r){if(!this.gridmap[o])return!0;var a=this.gridmap[o][r];this.is_occupied(o,r)&&!this.is_player(a)&&-1===t.inArray(a,e)&&(i=i.add(a),e.push(a))},this))},this)),i},r.on_start_overlapping_column=function(t){this.set_player(t,!1)},r.on_start_overlapping_row=function(t){this.set_player(!1,t)},r.on_stop_overlapping_column=function(t){this.set_player(t,!1);var i=this;this.for_each_widget_below(t,this.cells_occupied_by_player.rows[0],function(){i.move_widget_up(this,i.player_grid_data.size_y)})},r.on_stop_overlapping_row=function(t){this.set_player(!1,t);for(var i=this,e=this.cells_occupied_by_player.cols,s=0,r=e.length;r>s;s++)this.for_each_widget_below(e[s],t,function(){i.move_widget_up(this,i.player_grid_data.size_y)})},r.move_widget_to=function(i,e){var s=this,r=i.coords().grid;e-r.row;var o=this.widgets_below(i),a=this.can_move_to(r,r.col,e,i);return a===!1?!1:(this.remove_from_gridmap(r),r.row=e,this.add_to_gridmap(r),i.attr("data-row",e),this.$changed=this.$changed.add(i),o.each(function(i,e){var r=t(e),o=r.coords().grid,a=s.can_go_widget_up(o);a&&a!==o.row&&s.move_widget_to(r,a)}),this)},r.move_widget_up=function(i,e){var s=i.coords().grid,r=s.row,o=[];return e||(e=1),this.can_go_up(i)?(this.for_each_column_occupied(s,function(s){if(-1===t.inArray(i,o)){var a=i.coords().grid,n=r-e;if(n=this.can_go_up_to_row(a,s,n),!n)return!0;var h=this.widgets_below(i);this.remove_from_gridmap(a),a.row=n,this.add_to_gridmap(a),i.attr("data-row",a.row),this.$changed=this.$changed.add(i),o.push(i),h.each(t.proxy(function(i,s){this.move_widget_up(t(s),e)},this))}}),void 0):!1},r.move_widget_down=function(i,e){var s,r,o,a;if(0>=e)return!1;if(s=i.coords().grid,r=s.row,o=[],a=e,!i)return!1;if(-1===t.inArray(i,o)){var n=i.coords().grid,h=r+e,_=this.widgets_below(i);this.remove_from_gridmap(n),_.each(t.proxy(function(i,e){var s=t(e),r=s.coords().grid,o=this.displacement_diff(r,n,a);o>0&&this.move_widget_down(s,o)},this)),n.row=h,this.update_widget_position(n,i),i.attr("data-row",n.row),this.$changed=this.$changed.add(i),o.push(i)}},r.can_go_up_to_row=function(i,e,s){var r,o=this.gridmap,a=!0,n=[],h=i.row;if(this.for_each_column_occupied(i,function(t){for(o[t],n[t]=[],r=h;r--&&this.is_empty(t,r)&&!this.is_placeholder_in(t,r);)n[t].push(r);return n[t].length?void 0:(a=!1,!0)}),!a)return!1;for(r=s,r=1;h>r;r++){for(var _=!0,d=0,l=n.length;l>d;d++)n[d]&&-1===t.inArray(r,n[d])&&(_=!1);if(_===!0){a=r;break}}return a},r.displacement_diff=function(t,i,e){var s=t.row,r=[],o=i.row+i.size_y;this.for_each_column_occupied(t,function(t){for(var i=0,e=o;s>e;e++)this.is_empty(t,e)&&(i+=1);r.push(i)});var a=Math.max.apply(Math,r);return e-=a,e>0?e:0},r.widgets_below=function(i){var s=t.isPlainObject(i)?i:i.coords().grid,r=this;this.gridmap;var o=s.row+s.size_y-1,a=t([]);return this.for_each_column_occupied(s,function(i){r.for_each_widget_below(i,o,function(){return r.is_player(this)||-1!==t.inArray(this,a)?void 0:(a=a.add(this),!0)})}),e.sort_by_row_asc(a)},r.set_cells_player_occupies=function(t,i){return this.remove_from_gridmap(this.placeholder_grid_data),this.placeholder_grid_data.col=t,this.placeholder_grid_data.row=i,this.add_to_gridmap(this.placeholder_grid_data,this.$player),this},r.empty_cells_player_occupies=function(){return this.remove_from_gridmap(this.placeholder_grid_data),this},r.can_go_up=function(t){var i=t.coords().grid,e=i.row,s=e-1;this.gridmap;var r=!0;return 1===e?!1:(this.for_each_column_occupied(i,function(t){return this.is_widget(t,s),this.is_occupied(t,s)||this.is_player(t,s)||this.is_placeholder_in(t,s)||this.is_player_in(t,s)?(r=!1,!0):void 0}),r)},r.can_move_to=function(t,i,e,s){this.gridmap;var r=t.el,o={size_y:t.size_y,size_x:t.size_x,col:i,row:e},a=!0,n=i+t.size_x-1;return n>this.cols?!1:s&&e+t.size_y-1>s?!1:(this.for_each_cell_occupied(o,function(i,e){var s=this.is_widget(i,e);!s||t.el&&!s.is(r)||(a=!1)}),a)},r.get_targeted_columns=function(t){for(var i=(t||this.player_grid_data.col)+(this.player_grid_data.size_x-1),e=[],s=t;i>=s;s++)e.push(s);return e},r.get_targeted_rows=function(t){for(var i=(t||this.player_grid_data.row)+(this.player_grid_data.size_y-1),e=[],s=t;i>=s;s++)e.push(s);return e},r.get_cells_occupied=function(i){var e,s={cols:[],rows:[]};for(arguments[1]instanceof t&&(i=arguments[1].coords().grid),e=0;i.size_x>e;e++){var r=i.col+e;s.cols.push(r)}for(e=0;i.size_y>e;e++){var o=i.row+e;s.rows.push(o)}return s},r.for_each_cell_occupied=function(t,i){return this.for_each_column_occupied(t,function(e){this.for_each_row_occupied(t,function(t){i.call(this,e,t)})}),this},r.for_each_column_occupied=function(t,i){for(var e=0;t.size_x>e;e++){var s=t.col+e;i.call(this,s,t)}},r.for_each_row_occupied=function(t,i){for(var e=0;t.size_y>e;e++){var s=t.row+e;i.call(this,s,t)}},r._traversing_widgets=function(i,e,s,r,o){var a=this.gridmap;if(a[s]){var n,h,_=i+"/"+e;if(arguments[2]instanceof t){var d=arguments[2].coords().grid;s=d.col,r=d.row,o=arguments[3]}var l=[],c=r,g={"for_each/above":function(){for(;c--&&!(c>0&&this.is_widget(s,c)&&-1===t.inArray(a[s][c],l)&&(n=o.call(a[s][c],s,c),l.push(a[s][c]),n)););},"for_each/below":function(){for(c=r+1,h=a[s].length;h>c&&(!this.is_widget(s,c)||-1!==t.inArray(a[s][c],l)||(n=o.call(a[s][c],s,c),l.push(a[s][c]),!n));c++);}};g[_]&&g[_].call(this)}},r.for_each_widget_above=function(t,i,e){return this._traversing_widgets("for_each","above",t,i,e),this},r.for_each_widget_below=function(t,i,e){return this._traversing_widgets("for_each","below",t,i,e),this},r.get_highest_occupied_cell=function(){for(var t,i=this.gridmap,e=i[1].length,s=[],r=[],o=i.length-1;o>=1;o--)for(t=e-1;t>=1;t--)if(this.is_widget(o,t)){s.push(t),r.push(o);break}return{col:Math.max.apply(Math,r),row:Math.max.apply(Math,s)}},r.get_widgets_from=function(i,e){this.gridmap;var s=t();return i&&(s=s.add(this.$widgets.filter(function(){var e=t(this).attr("data-col");return e===i||e>i}))),e&&(s=s.add(this.$widgets.filter(function(){var i=t(this).attr("data-row");return i===e||i>e}))),s},r.set_dom_grid_height=function(t){if(t===void 0){var i=this.get_highest_occupied_cell().row;t=i*this.min_widget_height}return this.container_height=t,this.$el.css("height",this.container_height),this},r.set_dom_grid_width=function(t){t===void 0&&(t=this.get_highest_occupied_cell().col);var i=this.options.autogrow_cols?this.options.max_cols:this.cols;return t=Math.min(i,Math.max(t,this.options.min_cols)),this.container_width=t*this.min_widget_width,this.$el.css("width",this.container_width),this},r.generate_stylesheet=function(i){var s,r="",o=this.options.max_size_x||this.cols;i||(i={}),i.cols||(i.cols=this.cols),i.rows||(i.rows=this.rows),i.namespace||(i.namespace=this.options.namespace),i.widget_base_dimensions||(i.widget_base_dimensions=this.options.widget_base_dimensions),i.widget_margins||(i.widget_margins=this.options.widget_margins),i.min_widget_width=2*i.widget_margins[0]+i.widget_base_dimensions[0],i.min_widget_height=2*i.widget_margins[1]+i.widget_base_dimensions[1];var a=t.param(i);if(t.inArray(a,e.generated_stylesheets)>=0)return!1;for(this.generated_stylesheets.push(a),e.generated_stylesheets.push(a),s=i.cols;s>=0;s--)r+=i.namespace+' [data-col="'+(s+1)+'"] { left:'+(s*i.widget_base_dimensions[0]+s*i.widget_margins[0]+(s+1)*i.widget_margins[0])+"px; }\n";for(s=i.rows;s>=0;s--)r+=i.namespace+' [data-row="'+(s+1)+'"] { top:'+(s*i.widget_base_dimensions[1]+s*i.widget_margins[1]+(s+1)*i.widget_margins[1])+"px; }\n";for(var n=1;i.rows>=n;n++)r+=i.namespace+' [data-sizey="'+n+'"] { height:'+(n*i.widget_base_dimensions[1]+(n-1)*2*i.widget_margins[1])+"px; }\n";for(var h=1;o>=h;h++)r+=i.namespace+' [data-sizex="'+h+'"] { width:'+(h*i.widget_base_dimensions[0]+(h-1)*2*i.widget_margins[0])+"px; }\n";return this.remove_style_tags(),this.add_style_tag(r)},r.add_style_tag=function(t){var i=document,e=i.createElement("style");return i.getElementsByTagName("head")[0].appendChild(e),e.setAttribute("type","text/css"),e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t)),this.$style_tags=this.$style_tags.add(e),this},r.remove_style_tags=function(){var i=e.generated_stylesheets,s=this.generated_stylesheets;this.$style_tags.remove(),e.generated_stylesheets=t.map(i,function(i){return-1===t.inArray(i,s)?i:void 0})},r.generate_faux_grid=function(t,i){this.faux_grid=[],this.gridmap=[];var e,s;for(e=i;e>0;e--)for(this.gridmap[e]=[],s=t;s>0;s--)this.add_faux_cell(s,e);return this},r.add_faux_cell=function(i,e){var s=t({left:this.baseX+(e-1)*this.min_widget_width,top:this.baseY+(i-1)*this.min_widget_height,width:this.min_widget_width,height:this.min_widget_height,col:e,row:i,original_col:e,original_row:i}).coords();return t.isArray(this.gridmap[e])||(this.gridmap[e]=[]),this.gridmap[e][i]=!1,this.faux_grid.push(s),this},r.add_faux_rows=function(t){for(var i=this.rows,e=i+(t||1),s=e;s>i;s--)for(var r=this.cols;r>=1;r--)this.add_faux_cell(s,r);return this.rows=e,this.options.autogenerate_stylesheet&&this.generate_stylesheet(),this},r.add_faux_cols=function(t){var i=this.cols,e=i+(t||1);e=Math.min(e,this.options.max_cols);for(var s=i+1;e>=s;s++)for(var r=this.rows;r>=1;r--)this.add_faux_cell(r,s);return this.cols=e,this.options.autogenerate_stylesheet&&this.generate_stylesheet(),this},r.recalculate_faux_grid=function(){var i=this.$wrapper.width();return this.baseX=(t(window).width()-i)/2,this.baseY=this.$wrapper.offset().top,t.each(this.faux_grid,t.proxy(function(t,i){this.faux_grid[t]=i.update({left:this.baseX+(i.data.col-1)*this.min_widget_width,top:this.baseY+(i.data.row-1)*this.min_widget_height})},this)),this},r.get_widgets_from_DOM=function(){var i=this.$widgets.map(t.proxy(function(i,e){var s=t(e);return this.dom_to_coords(s)},this));i=e.sort_by_row_and_col_asc(i);var s=t(i).map(t.proxy(function(t,i){return this.register_widget(i)||null},this));return s.length&&this.$el.trigger("gridster:positionschanged"),this},r.generate_grid_and_stylesheet=function(){var i=this.$wrapper.width(),e=this.options.max_cols,s=Math.floor(i/this.min_widget_width)+this.options.extra_cols,r=this.$widgets.map(function(){return t(this).attr("data-col")}).get();r.length||(r=[0]);var o=Math.max.apply(Math,r);this.cols=Math.max(o,s,this.options.min_cols),1/0!==e&&e>=o&&this.cols>e&&(this.cols=e);var a=this.options.extra_rows;return this.$widgets.each(function(i,e){a+=+t(e).attr("data-sizey")}),this.rows=Math.max(a,this.options.min_rows),this.baseX=(t(window).width()-i)/2,this.baseY=this.$wrapper.offset().top,this.options.autogenerate_stylesheet&&this.generate_stylesheet(),this.generate_faux_grid(this.rows,this.cols)},r.destroy=function(i){return this.$el.removeData("gridster"),t(window).unbind(".gridster"),this.drag_api&&this.drag_api.destroy(),this.remove_style_tags(),i&&this.$el.remove(),this},t.fn.gridster=function(i){return this.each(function(){t(this).data("gridster")||t(this).data("gridster",new e(this,i))})},e}),function(t,i){"function"==typeof define&&define.amd?define(["jquery","gridster"],i):t.Gridster=i(t.$||t.jQuery,t.Gridster)}(this,function(t,i){var e=i.prototype;return e.widgets_in_col=function(t){if(!this.gridmap[t])return!1;for(var i=this.gridmap[t].length-1;i>=0;i--)if(this.is_widget(t,i)!==!1)return!0;return!1},e.widgets_in_row=function(t){for(var i=this.gridmap.length;i>=1;i--)if(this.is_widget(i,t)!==!1)return!0;return!1},e.widgets_in_range=function(i,e,s,r){var o,a,n,h,_=t([]);for(o=s;o>=i;o--)for(a=r;a>=e;a--)n=this.is_widget(o,a),n!==!1&&(h=n.data("coords").grid,h.col>=i&&s>=h.col&&h.row>=e&&r>=h.row&&(_=_.add(n)));return _},e.get_bottom_most_occupied_cell=function(){var t=0,i=0;return this.for_each_cell(function(e,s,r){e&&r>t&&(t=r,i=s)}),{col:i,row:t}},e.get_right_most_occupied_cell=function(){var t=0,i=0;return this.for_each_cell(function(e,s,r){return e?(t=r,i=s,!1):void 0}),{col:i,row:t}},e.for_each_cell=function(t,i){i||(i=this.gridmap);var e=i.length,s=i[1].length;t:for(var r=e-1;r>=1;r--)for(var o=s-1;o>=1;o--){var a=i[r]&&i[r][o];if(t){if(t.call(this,a,r,o)===!1)break t}else;}},e.next_position_in_range=function(t,e,s){t||(t=1),e||(e=1);for(var r,o=this.gridmap,a=o.length,n=[],h=1;a>h;h++){r=s||o[h].length;for(var _=1;r>=_;_++){var d=this.can_move_to({size_x:t,size_y:e},h,_,s);d&&n.push({col:h,row:_,size_y:e,size_x:t})}}return n.length>=1?i.sort_by_col_asc(n)[0]:!1},e.closest_to_right=function(t,i){if(!this.gridmap[t])return!1;for(var e=this.gridmap.length-1,s=t;e>=s;s++)if(this.gridmap[s][i])return{col:s,row:i};return!1},e.closest_to_left=function(t,i){if(this.gridmap.length-1,!this.gridmap[t])return!1;for(var e=t;e>=1;e--)if(this.gridmap[e][i])return{col:e,row:i};return!1},i}); | rtenshi/jsdelivr | files/gridster.js/0.5.3/jquery.gridster.with-extras.min.js | JavaScript | mit | 45,788 |
//! moment.js locale configuration
//! locale : canadian french (fr-ca)
//! author : Jonathan Abourbih : https://github.com/jonbca
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var fr_ca = moment.defineLocale('fr-ca', {
months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
monthsParseExact : true,
weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
weekdaysMin : 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'YYYY-MM-DD',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd D MMMM YYYY HH:mm'
},
calendar : {
sameDay: '[Aujourd\'hui à] LT',
nextDay: '[Demain à] LT',
nextWeek: 'dddd [à] LT',
lastDay: '[Hier à] LT',
lastWeek: 'dddd [dernier à] LT',
sameElse: 'L'
},
relativeTime : {
future : 'dans %s',
past : 'il y a %s',
s : 'quelques secondes',
m : 'une minute',
mm : '%d minutes',
h : 'une heure',
hh : '%d heures',
d : 'un jour',
dd : '%d jours',
M : 'un mois',
MM : '%d mois',
y : 'un an',
yy : '%d ans'
},
ordinalParse: /\d{1,2}(er|e)/,
ordinal : function (number) {
return number + (number === 1 ? 'er' : 'e');
}
});
return fr_ca;
})); | grazerjink/PhatHanhSach | PhatHanhSach.Web/Assets/vendors/moment/locale/fr-ca.js | JavaScript | mit | 2,097 |
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var parser = require('./parser');
/**
* Expose the constructor.
*/
exports = module.exports = Transport;
/**
* Transport constructor.
*
* @api public
*/
function Transport (mng, data, req) {
this.manager = mng;
this.id = data.id;
this.disconnected = false;
this.drained = true;
this.handleRequest(req);
};
/**
* Access the logger.
*
* @api public
*/
Transport.prototype.__defineGetter__('log', function () {
return this.manager.log;
});
/**
* Access the store.
*
* @api public
*/
Transport.prototype.__defineGetter__('store', function () {
return this.manager.store;
});
/**
* Handles a request when it's set.
*
* @api private
*/
Transport.prototype.handleRequest = function (req) {
this.log.debug('setting request', req.method, req.url);
this.req = req;
if (req.method == 'GET') {
this.socket = req.socket;
this.open = true;
this.drained = true;
this.setHeartbeatInterval();
this.setHandlers();
this.onSocketConnect();
}
};
/**
* Called when a connection is first set.
*
* @api private
*/
Transport.prototype.onSocketConnect = function () { };
/**
* Sets transport handlers
*
* @api private
*/
Transport.prototype.setHandlers = function () {
var self = this;
this.bound = {
end: this.onSocketEnd.bind(this)
, close: this.onSocketClose.bind(this)
, error: this.onSocketError.bind(this)
, drain: this.onSocketDrain.bind(this)
};
this.socket.on('end', this.bound.end);
this.socket.on('close', this.bound.close);
this.socket.on('error', this.bound.error);
this.socket.on('drain', this.bound.drain);
this.handlersSet = true;
};
/**
* Removes transport handlers
*
* @api private
*/
Transport.prototype.clearHandlers = function () {
if (this.handlersSet) {
this.socket.removeListener('end', this.bound.end);
this.socket.removeListener('close', this.bound.close);
this.socket.removeListener('error', this.bound.error);
this.socket.removeListener('drain', this.bound.drain);
}
};
/**
* Called when the connection dies
*
* @api private
*/
Transport.prototype.onSocketEnd = function () {
this.end('socket end');
};
/**
* Called when the connection dies
*
* @api private
*/
Transport.prototype.onSocketClose = function (error) {
this.end(error ? 'socket error' : 'socket close');
};
/**
* Called when the connection has an error.
*
* @api private
*/
Transport.prototype.onSocketError = function (err) {
if (this.open) {
this.socket.destroy();
this.onClose();
}
this.log.info('socket error ' + err.stack);
};
/**
* Called when the connection is drained.
*
* @api private
*/
Transport.prototype.onSocketDrain = function () {
this.drained = true;
};
/**
* Called upon receiving a heartbeat packet.
*
* @api private
*/
Transport.prototype.onHeartbeatClear = function () {
this.clearHeartbeatTimeout();
this.setHeartbeatInterval();
};
/**
* Called upon a forced disconnection.
*
* @api private
*/
Transport.prototype.onForcedDisconnect = function () {
if (!this.disconnected) {
this.log.info('transport end by forced client disconnection');
if (this.open) {
this.packet({ type: 'disconnect' });
}
this.end('booted');
}
};
/**
* Dispatches a packet.
*
* @api private
*/
Transport.prototype.onDispatch = function (packet, volatile) {
if (volatile) {
this.writeVolatile(packet);
} else {
this.write(packet);
}
};
/**
* Sets the close timeout.
*/
Transport.prototype.setCloseTimeout = function () {
if (!this.closeTimeout) {
var self = this;
this.closeTimeout = setTimeout(function () {
self.log.debug('fired close timeout for client', self.id);
self.closeTimeout = null;
self.end('close timeout');
}, this.manager.get('close timeout') * 1000);
this.log.debug('set close timeout for client', this.id);
}
};
/**
* Clears the close timeout.
*/
Transport.prototype.clearCloseTimeout = function () {
if (this.closeTimeout) {
clearTimeout(this.closeTimeout);
this.closeTimeout = null;
this.log.debug('cleared close timeout for client', this.id);
}
};
/**
* Sets the heartbeat timeout
*/
Transport.prototype.setHeartbeatTimeout = function () {
if (!this.heartbeatTimeout && this.manager.enabled('heartbeats')) {
var self = this;
this.heartbeatTimeout = setTimeout(function () {
self.log.debug('fired heartbeat timeout for client', self.id);
self.heartbeatTimeout = null;
self.end('heartbeat timeout');
}, this.manager.get('heartbeat timeout') * 1000);
this.log.debug('set heartbeat timeout for client', this.id);
}
};
/**
* Clears the heartbeat timeout
*
* @param text
*/
Transport.prototype.clearHeartbeatTimeout = function () {
if (this.heartbeatTimeout && this.manager.enabled('heartbeats')) {
clearTimeout(this.heartbeatTimeout);
this.heartbeatTimeout = null;
this.log.debug('cleared heartbeat timeout for client', this.id);
}
};
/**
* Sets the heartbeat interval. To be called when a connection opens and when
* a heartbeat is received.
*
* @api private
*/
Transport.prototype.setHeartbeatInterval = function () {
if (!this.heartbeatInterval && this.manager.enabled('heartbeats')) {
var self = this;
this.heartbeatInterval = setTimeout(function () {
self.heartbeat();
self.heartbeatInterval = null;
}, this.manager.get('heartbeat interval') * 1000);
this.log.debug('set heartbeat interval for client', this.id);
}
};
/**
* Clears all timeouts.
*
* @api private
*/
Transport.prototype.clearTimeouts = function () {
this.clearCloseTimeout();
this.clearHeartbeatTimeout();
this.clearHeartbeatInterval();
};
/**
* Sends a heartbeat
*
* @api private
*/
Transport.prototype.heartbeat = function () {
if (this.open) {
this.log.debug('emitting heartbeat for client', this.id);
this.packet({ type: 'heartbeat' });
this.setHeartbeatTimeout();
}
return this;
};
/**
* Handles a message.
*
* @param {Object} packet object
* @api private
*/
Transport.prototype.onMessage = function (packet) {
var current = this.manager.transports[this.id];
if ('heartbeat' == packet.type) {
this.log.debug('got heartbeat packet');
if (current && current.open) {
current.onHeartbeatClear();
} else {
this.store.publish('heartbeat-clear', this.id);
}
} else {
if ('disconnect' == packet.type && packet.endpoint == '') {
this.log.debug('got disconnection packet');
if (current) {
current.onForcedDisconnect();
} else {
this.store.publish('disconnect-force', this.id);
}
return;
}
if (packet.id && packet.ack != 'data') {
this.log.debug('acknowledging packet automatically');
var ack = parser.encodePacket({
type: 'ack'
, ackId: packet.id
, endpoint: packet.endpoint || ''
});
if (current && current.open) {
current.onDispatch(ack);
} else {
this.manager.onClientDispatch(this.id, ack);
this.store.publish('dispatch-remote', this.id, ack);
}
}
// handle packet locally or publish it
if (current) {
this.manager.onClientMessage(this.id, packet);
} else {
this.store.publish('message-remote', this.id, packet);
}
}
};
/**
* Clears the heartbeat interval
*
* @api private
*/
Transport.prototype.clearHeartbeatInterval = function () {
if (this.heartbeatInterval && this.manager.enabled('heartbeats')) {
clearTimeout(this.heartbeatInterval);
this.heartbeatInterval = null;
this.log.debug('cleared heartbeat interval for client', this.id);
}
};
/**
* Finishes the connection and makes sure client doesn't reopen
*
* @api private
*/
Transport.prototype.disconnect = function (reason) {
this.packet({ type: 'disconnect' });
this.end(reason);
return this;
};
/**
* Closes the connection.
*
* @api private
*/
Transport.prototype.close = function () {
if (this.open) {
this.doClose();
this.onClose();
}
};
/**
* Called upon a connection close.
*
* @api private
*/
Transport.prototype.onClose = function () {
if (this.open) {
this.setCloseTimeout();
this.clearHandlers();
this.open = false;
this.manager.onClose(this.id);
this.store.publish('close', this.id);
}
};
/**
* Cleans up the connection, considers the client disconnected.
*
* @api private
*/
Transport.prototype.end = function (reason) {
if (!this.disconnected) {
this.log.info('transport end (' + reason + ')');
var local = this.manager.transports[this.id];
this.close();
this.clearTimeouts();
this.disconnected = true;
if (local) {
this.manager.onClientDisconnect(this.id, reason);
}
this.store.publish('disconnect-remote', this.id, reason);
}
};
/**
* Signals that the transport should pause and buffer data.
*
* @api public
*/
Transport.prototype.discard = function () {
this.log.debug('discarding transport');
this.discarded = true;
this.clearTimeouts();
this.clearHandlers();
return this;
};
/**
* Writes an error packet with the specified reason and advice.
*
* @param {Number} advice
* @param {Number} reason
* @api public
*/
Transport.prototype.error = function (reason, advice) {
this.packet({
type: 'error'
, reason: reason
, advice: advice
});
this.log.warn(reason, advice ? ('client should ' + advice) : '');
this.end('error');
};
/**
* Write a packet.
*
* @api public
*/
Transport.prototype.packet = function (obj) {
return this.write(parser.encodePacket(obj));
};
/**
* Writes a volatile message.
*
* @api private
*/
Transport.prototype.writeVolatile = function (msg) {
if (this.open) {
if (this.drained) {
this.write(msg);
} else {
this.log.debug('ignoring volatile packet, buffer not drained');
}
} else {
this.log.debug('ignoring volatile packet, transport not open');
}
};
| hieuvoquang87/ngHub | node_modules/karma/node_modules/socket.io/lib/transport.js | JavaScript | mit | 10,142 |
//
// M2AppDelegate.m
// m2048
//
// Created by Danqing on 3/16/14.
// Copyright (c) 2014 Danqing. All rights reserved.
//
#import "M2AppDelegate.h"
#import <BuddyBuildSDK/BuddyBuildSDK.h>
#import "buddybuild Demo/BuddyBuildDemoAppHasCrashedViewController.h"
@implementation M2AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(@"didFinishLaunchingWithOptions - setting up BuddyBuildSDK");
[BuddyBuildSDK setup];
application.statusBarHidden = YES;
[BuddyBuildSDK setScreenshotAllowedCallback:^BOOL{
return self.screenshottingAllowed;
}];
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
[BuddyBuildSDK setScreenshotFeedbackSentCallback:^{
[userDefaults setBool:YES forKey:@"has_sent_feedback"];
[userDefaults synchronize];
[[NSNotificationCenter defaultCenter] postNotificationName:@"BUDDYBUILD_FEEDBACK_SENT" object:nil];
}];
typedef void (^ScreenshotCallback)(NSNotification* note);
ScreenshotCallback callback = ^(NSNotification* note) {
if (!self.screenshottingAllowed) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Hold your horses..." message:@"Tap OK before taking the screenshot" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Got it", nil];
[alert show];
}
};
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationUserDidTakeScreenshotNotification
object:nil
queue:mainQueue
usingBlock:callback];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(@"applicationWillResignActive");
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"applicationDidEnterBackground");
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
NSLog(@"applicationWillEnterForeground");
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"applicationDidBecomeActive");
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
NSLog(@"applicationWillTerminate");
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)sendNotification:(NSString*)notification {
NSString* endpoint = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"BUDDYBUILD_ENDPOINT"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* appID = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"BUDDYBUILD_APP_ID"];
NSString* url = [NSString stringWithFormat:@"%@/api/demo/%@?appID=%@", endpoint, notification, appID];
NSLog(@"url = %@", url);
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[NSURLConnection connectionWithRequest:request delegate:nil];
}
@end
| test-driver/hang-happy-unknown | m2048/M2AppDelegate.m | Matlab | mit | 4,292 |
.selectize-control.plugin-drag_drop.multi>.selectize-input>div.ui-sortable-placeholder{background:#f2f2f2!important;background:rgba(0,0,0,.06)!important;border:0!important;visibility:visible!important;-webkit-box-shadow:inset 0 0 12px 4px #fff;box-shadow:inset 0 0 12px 4px #fff}.selectize-control.plugin-drag_drop .ui-sortable-placeholder::after{content:'!';visibility:hidden}.selectize-control.plugin-drag_drop .ui-sortable-helper{-webkit-box-shadow:0 2px 5px rgba(0,0,0,.2);box-shadow:0 2px 5px rgba(0,0,0,.2)}.selectize-dropdown-header{position:relative;background:#f8f8f8;border-bottom:1px solid #d0d0d0;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.selectize-dropdown-header-close{position:absolute;top:50%;right:12px;margin-top:-12px;font-size:20px!important;line-height:20px;color:#333;opacity:.4}.selectize-dropdown-header-close:hover{color:#000}.selectize-dropdown.plugin-optgroup_columns .optgroup{float:left;border-top:0 none;border-right:1px solid #f2f2f2;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.selectize-dropdown.plugin-optgroup_columns .optgroup:last-child{border-right:0 none}.selectize-dropdown.plugin-optgroup_columns .optgroup:before{display:none}.selectize-dropdown.plugin-optgroup_columns .optgroup-header{border-top:0 none}.selectize-control.plugin-remove_button [data-value]{position:relative;padding-right:24px!important}.selectize-control.plugin-remove_button [data-value] .remove{position:absolute;top:0;right:0;bottom:0;display:inline-block;width:17px;padding:1px 0 0;font-size:12px;font-weight:700;color:inherit;text-align:center;text-decoration:none;vertical-align:middle;border-left:1px solid transparent;-webkit-border-radius:0 2px 2px 0;-moz-border-radius:0 2px 2px 0;border-radius:0 2px 2px 0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.selectize-control.plugin-remove_button [data-value] .remove:hover{background:rgba(0,0,0,.05)}.selectize-control.plugin-remove_button [data-value].active .remove{border-left-color:transparent}.selectize-control{position:relative}.selectize-dropdown,.selectize-input,.selectize-input input{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;-webkit-font-smoothing:inherit;line-height:20px;color:#333}.selectize-control.single .selectize-input.focus,.selectize-input{display:inline-block;cursor:text;background:#fff}.selectize-input{position:relative;z-index:1;display:inline-block;width:100%;padding:6px 12px;overflow:hidden;border:1px solid #ccc;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:none;box-shadow:none;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.selectize-control.multi .selectize-input.has-items{padding:5px 12px 2px}.selectize-input.full{background-color:#fff}.selectize-input.disabled,.selectize-input.disabled *{cursor:default!important}.selectize-input>*{display:-moz-inline-stack;display:inline-block;vertical-align:baseline;zoom:1}.selectize-control.multi .selectize-input>div{padding:1px 3px;margin:0 3px 3px 0;color:#333;cursor:pointer;background:#efefef;border:0 solid transparent}.selectize-control.multi .selectize-input>div.active{color:#fff;background:#428bca;border:0 solid transparent}.selectize-control.multi .selectize-input.disabled>div,.selectize-control.multi .selectize-input.disabled>div.active{color:gray;background:#fff;border:0 solid rgba(77,77,77,0)}.selectize-input>input{max-width:100%!important;max-height:none!important;min-height:0!important;padding:0!important;margin:0!important;line-height:inherit!important;text-indent:0!important;background:none!important;border:0!important;-webkit-box-shadow:none!important;box-shadow:none!important;-webkit-user-select:auto!important}.selectize-input>input:focus{outline:0!important}.selectize-input::after{display:block;clear:left;content:' '}.selectize-input.dropdown-active::before{position:absolute;right:0;bottom:0;left:0;height:1px;background:#fff;content:' '}.selectize-dropdown{position:absolute;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.selectize-dropdown [data-selectable]{overflow:hidden;cursor:pointer}.selectize-dropdown [data-selectable] .highlight{background:rgba(255,237,40,.4);-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px}.selectize-dropdown .optgroup-header,.selectize-dropdown [data-selectable]{padding:3px 12px}.selectize-dropdown .optgroup:first-child .optgroup-header{border-top:0 none}.selectize-dropdown .optgroup-header{color:#999;cursor:default;background:#fff}.selectize-dropdown .active{color:#fff;background-color:#428bca}.selectize-dropdown .active.create{color:#fff}.selectize-dropdown .create{color:rgba(51,51,51,.5)}.selectize-dropdown-content{max-height:200px;overflow-x:hidden;overflow-y:auto}.selectize-control.single .selectize-input,.selectize-control.single .selectize-input input{cursor:pointer}.selectize-control.single .selectize-input.focus,.selectize-control.single .selectize-input.focus input{cursor:text}.selectize-control.single .selectize-input:after{position:absolute;top:50%;right:17px;display:block;width:0;height:0;margin-top:-3px;border-color:#000 transparent transparent;border-style:solid;border-width:5px 5px 0;content:' '}.selectize-control.single .selectize-input.dropdown-active:after{margin-top:-4px;border-color:transparent transparent #000;border-width:0 5px 5px}.selectize-control .selectize-input.disabled{background-color:#fff;opacity:.5}.selectize-dropdown,.selectize-dropdown.form-control{z-index:1000;height:auto;padding:0;margin:2px 0 0;background:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.selectize-dropdown .optgroup-header{font-size:12px;line-height:1.428571429}.selectize-dropdown .optgroup:first-child:before{display:none}.selectize-dropdown .optgroup:before{display:block;height:1px;margin:9px -12px;overflow:hidden;background-color:#e5e5e5;content:' '}.selectize-dropdown-content{padding:5px 0}.selectize-dropdown-header{padding:6px 12px}.selectize-input{min-height:34px}.selectize-input.dropdown-active{-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.selectize-input.dropdown-active::before{display:none}.selectize-input.focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.selectize-control.multi .selectize-input.has-items{padding-right:9px;padding-left:9px}.selectize-control.multi .selectize-input>div{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.form-control.selectize-control{height:auto;padding:0;background:0 0;border:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;box-shadow:none} | sajochiu/cdnjs | ajax/libs/selectize.js/0.7.7/css/selectize.bootstrap3.min.css | CSS | mit | 6,996 |
/*!
* socket.io-node
* Copyright(c) 2011 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
(function (module, io, should) {
module.exports = {
'add listeners': function () {
var event = new io.EventEmitter
, calls = 0;
event.on('test', function (a, b) {
++calls;
a.should().eql('a');
b.should().eql('b');
});
event.emit('test', 'a', 'b');
calls.should().eql(1);
event.on.should().eql(event.addListener);
},
'remove listener': function () {
var event = new io.EventEmitter;
function empty () { }
event.on('test', empty);
event.on('test:more', empty);
event.removeAllListeners('test');
event.listeners('test').should().eql([]);
event.listeners('test:more').should().eql([empty]);
},
'remove all listeners with no arguments': function () {
var event = new io.EventEmitter;
function empty () { }
event.on('test', empty);
event.on('test:more', empty);
event.removeAllListeners();
event.listeners('test').should().eql([]);
event.listeners('test:more').should().eql([]);
},
'remove listeners functions': function () {
var event = new io.EventEmitter
, calls = 0;
function one () { ++calls }
function two () { ++calls }
function three () { ++calls }
event.on('one', one);
event.removeListener('one', one);
event.listeners('one').should().eql([]);
event.on('two', two);
event.removeListener('two', one);
event.listeners('two').should().eql([two]);
event.on('three', three);
event.on('three', two);
event.removeListener('three', three);
event.listeners('three').should().eql([two]);
},
'number of arguments': function () {
var event = new io.EventEmitter
, number = [];
event.on('test', function () {
number.push(arguments.length);
});
event.emit('test');
event.emit('test', null);
event.emit('test', null, null);
event.emit('test', null, null, null);
event.emit('test', null, null, null, null);
event.emit('test', null, null, null, null, null);
[0, 1, 2, 3, 4, 5].should().eql(number);
},
'once': function () {
var event = new io.EventEmitter
, calls = 0;
event.once('test', function (a, b) {
++calls;
});
event.emit('test', 'a', 'b');
event.emit('test', 'a', 'b');
event.emit('test', 'a', 'b');
function removed () {
should().fail('not removed');
};
event.once('test:removed', removed);
event.removeListener('test:removed', removed);
event.emit('test:removed');
calls.should().eql(1);
}
};
})(
'undefined' == typeof module ? module = {} : module
, 'undefined' == typeof io ? require('socket.io-client') : io
, 'undefined' == typeof should || !should.fail ? require('should') : should
);
| pncifra/gdi | node_modules/socket.io/node_modules/socket.io-client/test/events.test.js | JavaScript | mit | 2,988 |
YUI.add("node-base",function(e){var d=["hasClass","addClass","removeClass","replaceClass","toggleClass"];e.Node.importMethod(e.DOM,d);e.NodeList.importMethod(e.Node.prototype,d);var c=e.Node,b=e.DOM;c.create=function(f,g){if(g&&g._node){g=g._node;}return e.one(b.create(f,g));};e.mix(c.prototype,{create:c.create,insert:function(g,f){this._insert(g,f);return this;},_insert:function(i,g){var h=this._node,f=null;if(typeof g=="number"){g=this._node.childNodes[g];}else{if(g&&g._node){g=g._node;}}if(i&&typeof i!="string"){i=i._node||i._nodes||i;}f=b.addHTML(h,i,g);return f;},prepend:function(f){return this.insert(f,0);},append:function(f){return this.insert(f,null);},appendChild:function(f){return c.scrubVal(this._insert(f));},insertBefore:function(g,f){return e.Node.scrubVal(this._insert(g,f));},appendTo:function(f){e.one(f).append(this);return this;},setContent:function(f){this._insert(f,"replace");return this;},getContent:function(f){return this.get("innerHTML");}});e.Node.prototype.setHTML=e.Node.prototype.setContent;e.Node.prototype.getHTML=e.Node.prototype.getContent;e.NodeList.importMethod(e.Node.prototype,["append","insert","appendChild","insertBefore","prepend","setContent","getContent","setHTML","getHTML"]);var c=e.Node,b=e.DOM;c.ATTRS={text:{getter:function(){return b.getText(this._node);},setter:function(f){b.setText(this._node,f);return f;}},"for":{getter:function(){return b.getAttribute(this._node,"for");},setter:function(f){b.setAttribute(this._node,"for",f);return f;}},"options":{getter:function(){return this._node.getElementsByTagName("option");}},"children":{getter:function(){var j=this._node,h=j.children,k,g,f;if(!h){k=j.childNodes;h=[];for(g=0,f=k.length;g<f;++g){if(k[g].tagName){h[h.length]=k[g];}}}return e.all(h);}},value:{getter:function(){return b.getValue(this._node);},setter:function(f){b.setValue(this._node,f);return f;}}};e.Node.importMethod(e.DOM,["setAttribute","getAttribute"]);var c=e.Node;var a=e.NodeList;c.DOM_EVENTS={abort:1,beforeunload:1,blur:1,change:1,click:1,close:1,command:1,contextmenu:1,dblclick:1,DOMMouseScroll:1,drag:1,dragstart:1,dragenter:1,dragover:1,dragleave:1,dragend:1,drop:1,error:1,focus:1,key:1,keydown:1,keypress:1,keyup:1,load:1,message:1,mousedown:1,mouseenter:1,mouseleave:1,mousemove:1,mousemultiwheel:1,mouseout:1,mouseover:1,mouseup:1,mousewheel:1,orientationchange:1,reset:1,resize:1,select:1,selectstart:1,submit:1,scroll:1,textInput:1,unload:1};e.mix(c.DOM_EVENTS,e.Env.evt.plugins);e.augment(c,e.EventTarget);e.mix(c.prototype,{purge:function(g,f){e.Event.purgeElement(this._node,g,f);return this;}});e.mix(e.NodeList.prototype,{_prepEvtArgs:function(i,h,g){var f=e.Array(arguments,0,true);if(f.length<2){f[2]=this._nodes;}else{f.splice(2,0,this._nodes);}f[3]=g||this;return f;},on:function(h,g,f){return e.on.apply(e,this._prepEvtArgs.apply(this,arguments));},once:function(h,g,f){return e.once.apply(e,this._prepEvtArgs.apply(this,arguments));},after:function(h,g,f){return e.after.apply(e,this._prepEvtArgs.apply(this,arguments));},onceAfter:function(h,g,f){return e.onceAfter.apply(e,this._prepEvtArgs.apply(this,arguments));}});a.importMethod(e.Node.prototype,["detach","detachAll"]);e.mix(e.Node.ATTRS,{offsetHeight:{setter:function(f){e.DOM.setHeight(this._node,f);return f;},getter:function(){return this._node.offsetHeight;}},offsetWidth:{setter:function(f){e.DOM.setWidth(this._node,f);return f;},getter:function(){return this._node.offsetWidth;}}});e.mix(e.Node.prototype,{sizeTo:function(f,g){var i;if(arguments.length<2){i=e.one(f);f=i.get("offsetWidth");g=i.get("offsetHeight");}this.setAttrs({offsetWidth:f,offsetHeight:g});}});var c=e.Node;e.mix(c.prototype,{show:function(f){f=arguments[arguments.length-1];this.toggleView(true,f);return this;},_show:function(){this.setStyle("display","");},_isHidden:function(){return e.DOM.getStyle(this._node,"display")==="none";},toggleView:function(f,g){this._toggleView.apply(this,arguments);return this;},_toggleView:function(f,g){g=arguments[arguments.length-1];if(typeof f!="boolean"){f=(this._isHidden())?1:0;}if(f){this._show();}else{this._hide();}if(typeof g=="function"){g.call(this);}return this;},hide:function(f){f=arguments[arguments.length-1];this.toggleView(false,f);return this;},_hide:function(){this.setStyle("display","none");}});e.NodeList.importMethod(e.Node.prototype,["show","hide","toggleView"]);if(!e.config.doc.documentElement.hasAttribute){e.Node.prototype.hasAttribute=function(f){if(f==="value"){if(this.get("value")!==""){return true;}}return !!(this._node.attributes[f]&&this._node.attributes[f].specified);};}e.Node.prototype.focus=function(){try{this._node.focus();}catch(f){}return this;};e.Node.ATTRS.type={setter:function(g){if(g==="hidden"){try{this._node.type="hidden";}catch(f){this.setStyle("display","none");this._inputType="hidden";}}else{try{this._node.type=g;}catch(f){}}return g;},getter:function(){return this._inputType||this._node.type;},_bypassProxy:true};if(e.config.doc.createElement("form").elements.nodeType){e.Node.ATTRS.elements={getter:function(){return this.all("input, textarea, button, select");}};}e.mix(e.Node.prototype,{_initData:function(){if(!("_data" in this)){this._data={};}},getData:function(g){this._initData();var h=this._data,f=h;if(arguments.length){if(g in h){f=h[g];}else{f=this._getDataAttribute(g);}}else{if(typeof h=="object"&&h!==null){f={};e.Object.each(h,function(i,j){f[j]=i;});f=this._getDataAttributes(f);}}return f;},_getDataAttributes:function(k){k=k||{};var l=0,j=this._node.attributes,f=j.length,m=this.DATA_PREFIX,h=m.length,g;while(l<f){g=j[l].name;if(g.indexOf(m)===0){g=g.substr(h);if(!(g in k)){k[g]=this._getDataAttribute(g);}}l+=1;}return k;},_getDataAttribute:function(g){var g=this.DATA_PREFIX+g,h=this._node,f=h.attributes,i=f&&f[g]&&f[g].value;return i;},setData:function(f,g){this._initData();if(arguments.length>1){this._data[f]=g;}else{this._data=f;}return this;},clearData:function(f){if("_data" in this){if(typeof f!="undefined"){delete this._data[f];
}else{delete this._data;}}return this;}});e.mix(e.NodeList.prototype,{getData:function(g){var f=(arguments.length)?[g]:[];return this._invoke("getData",f,true);},setData:function(g,h){var f=(arguments.length>1)?[g,h]:[g];return this._invoke("setData",f);},clearData:function(g){var f=(arguments.length)?[g]:[];return this._invoke("clearData",[g]);}});},"@VERSION@",{requires:["dom-base","node-core","event-base"]}); | mayur404/cdnjs | ajax/libs/yui/3.5.0/node-base/node-base-min.js | JavaScript | mit | 6,419 |
YUI.add("base-build",function(g){var c=g.Base,a=g.Lang,b="initializer",e="destructor",f,d=function(j,i,h){if(h[j]){i[j]=(i[j]||[]).concat(h[j]);}};c._build=function(h,o,t,x,w,q){var y=c._build,j=y._ctor(o,q),m=y._cfg(o,q,t),v=y._mixCust,k=j._yuibuild.dynamic,p,n,u,z,s,r;for(p=0,n=t.length;p<n;p++){u=t[p];z=u.prototype;s=z[b];r=z[e];delete z[b];delete z[e];g.mix(j,u,true,null,1);v(j,u,m);if(s){z[b]=s;}if(r){z[e]=r;}j._yuibuild.exts.push(u);}if(x){g.mix(j.prototype,x,true);}if(w){g.mix(j,y._clean(w,m),true);v(j,w,m);}j.prototype.hasImpl=y._impl;if(k){j.NAME=h;j.prototype.constructor=j;}return j;};f=c._build;g.mix(f,{_mixCust:function(h,t,p){var o,j,q,k,m,n;if(p){o=p.aggregates;j=p.custom;q=p.statics;}if(q){g.mix(h,t,true,q);}if(o){for(n=0,m=o.length;n<m;n++){k=o[n];if(!h.hasOwnProperty(k)&&t.hasOwnProperty(k)){h[k]=a.isArray(t[k])?[]:{};}g.aggregate(h,t,true,[k]);}}if(j){for(n in j){if(j.hasOwnProperty(n)){j[n](n,h,t);}}}},_tmpl:function(h){function i(){i.superclass.constructor.apply(this,arguments);}g.extend(i,h);return i;},_impl:function(n){var q=this._getClasses(),p,k,h,o,r,m;for(p=0,k=q.length;p<k;p++){h=q[p];if(h._yuibuild){o=h._yuibuild.exts;r=o.length;for(m=0;m<r;m++){if(o[m]===n){return true;}}}}return false;},_ctor:function(h,i){var k=(i&&false===i.dynamic)?false:true,l=(k)?f._tmpl(h):h,j=l._yuibuild;if(!j){j=l._yuibuild={};}j.id=j.id||null;j.exts=j.exts||[];j.dynamic=k;return l;},_cfg:function(m,q,n){var k=[],p={},v=[],h,t=(q&&q.aggregates),u=(q&&q.custom),r=(q&&q.statics),s=m,o,j;while(s&&s.prototype){h=s._buildCfg;if(h){if(h.aggregates){k=k.concat(h.aggregates);}if(h.custom){g.mix(p,h.custom,true);}if(h.statics){v=v.concat(h.statics);}}s=s.superclass?s.superclass.constructor:null;}if(n){for(o=0,j=n.length;o<j;o++){s=n[o];h=s._buildCfg;if(h){if(h.aggregates){k=k.concat(h.aggregates);}if(h.custom){g.mix(p,h.custom,true);}if(h.statics){v=v.concat(h.statics);}}}}if(t){k=k.concat(t);}if(u){g.mix(p,q.cfgBuild,true);}if(r){v=v.concat(r);}return{aggregates:k,custom:p,statics:v};},_clean:function(q,j){var p,k,h,n=g.merge(q),o=j.aggregates,m=j.custom;for(p in m){if(n.hasOwnProperty(p)){delete n[p];}}for(k=0,h=o.length;k<h;k++){p=o[k];if(n.hasOwnProperty(p)){delete n[p];}}return n;}});c.build=function(j,h,k,i){return f(j,h,k,null,null,i);};c.create=function(h,k,j,i,l){return f(h,k,j,i,l);};c.mix=function(h,i){return f(null,h,i,null,null,{dynamic:false});};c._buildCfg={custom:{ATTRS:function(m,k,i){k.ATTRS=k.ATTRS||{};if(i.ATTRS){var j=i.ATTRS,l=k.ATTRS,h;for(h in j){if(j.hasOwnProperty(h)){l[h]=l[h]||{};g.mix(l[h],j[h],true);}}}},_NON_ATTRS_CFG:d},aggregates:["_PLUG","_UNPLUG"]};},"@VERSION@",{requires:["base-base"]}); | Timbioz/cdnjs | ajax/libs/yui/3.6.0/base-build/base-build-min.js | JavaScript | mit | 2,665 |
;(function(){
// CommonJS require()
function require(p){
var path = require.resolve(p)
, mod = require.modules[path];
if (!mod) throw new Error('failed to require "' + p + '"');
if (!mod.exports) {
mod.exports = {};
mod.call(mod.exports, mod, mod.exports, require.relative(path));
}
return mod.exports;
}
require.modules = {};
require.resolve = function (path){
var orig = path
, reg = path + '.js'
, index = path + '/index.js';
return require.modules[reg] && reg
|| require.modules[index] && index
|| orig;
};
require.register = function (path, fn){
require.modules[path] = fn;
};
require.relative = function (parent) {
return function(p){
if ('.' != p.charAt(0)) return require(p);
var path = parent.split('/')
, segs = p.split('/');
path.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
else if ('.' != seg) path.push(seg);
}
return require(path.join('/'));
};
};
require.register("browser/debug.js", function(module, exports, require){
module.exports = function(type){
return function(){
}
};
}); // module: browser/debug.js
require.register("browser/diff.js", function(module, exports, require){
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
var JsDiff = (function() {
/*jshint maxparams: 5*/
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&');
n = n.replace(/</g, '<');
n = n.replace(/>/g, '>');
n = n.replace(/"/g, '"');
return n;
}
var Diff = function(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
};
Diff.prototype = {
diff: function(oldString, newString) {
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return [{ value: newString }];
}
if (!newString) {
return [{ value: oldString, removed: true }];
}
if (!oldString) {
return [{ value: newString, added: true }];
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
return bestPath[0].components;
}
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
var basePath;
var addPath = bestPath[diagonalPath-1],
removePath = bestPath[diagonalPath+1];
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined;
}
var canAdd = addPath && addPath.newPos+1 < newLen;
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
} else {
basePath = clonePath(addPath);
basePath.newPos++;
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
}
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
return basePath.components;
} else {
bestPath[diagonalPath] = basePath;
}
}
}
},
pushComponent: function(components, value, added, removed) {
var last = components[components.length-1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1] =
{value: this.join(last.value, value), added: added, removed: removed };
} else {
components.push({value: value, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
newPos++;
oldPos++;
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
return true;
} else {
return left === right;
}
},
join: function(left, right) {
return left + right;
},
tokenize: function(value) {
return value;
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
LineDiff.tokenize = function(value) {
return value.split(/^/m);
};
return {
Diff: Diff,
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
ret.push('Index: ' + fileName);
ret.push('===================================================================');
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
}
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
function contextLines(lines) {
return lines.map(function(entry) { return ' ' + entry; });
}
function eofNL(curRange, i, current) {
var last = diff[diff.length-2],
isLast = i === diff.length-2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
// Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
var prev = diff[i-1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
eofNL(curRange, i, current);
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0; newRangeStart = 0; curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n');
var diff = [];
var remEOFNL = false,
addEOFNL = false;
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
if(diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
} else if(diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') {
remEOFNL = true;
} else if(diffstr[i-1][0] === '-') {
addEOFNL = true;
}
}
}
var str = oldStr.split('\n');
for (var i = diff.length - 1; i >= 0; i--) {
var d = diff[i];
for (var j = 0; j < d.oldlength; j++) {
if(str[d.start-1+j] !== d.oldlines[j]) {
return false;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if (remEOFNL) {
while (!str[str.length-1]) {
str.pop();
}
} else if (addEOFNL) {
str.push('');
}
return str.join('\n');
},
convertChangesToXML: function(changes){
var ret = [];
for ( var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){
var ret = [], change;
for ( var i = 0; i < changes.length; i++) {
change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
}
return ret;
}
};
})();
if (typeof module !== 'undefined') {
module.exports = JsDiff;
}
}); // module: browser/diff.js
require.register("browser/events.js", function(module, exports, require){
/**
* Module exports.
*/
exports.EventEmitter = EventEmitter;
/**
* Check if `obj` is an array.
*/
function isArray(obj) {
return '[object Array]' == {}.toString.call(obj);
}
/**
* Event emitter constructor.
*
* @api public
*/
function EventEmitter(){};
/**
* Adds a listener.
*
* @api public
*/
EventEmitter.prototype.on = function (name, fn) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = fn;
} else if (isArray(this.$events[name])) {
this.$events[name].push(fn);
} else {
this.$events[name] = [this.$events[name], fn];
}
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
/**
* Adds a volatile listener.
*
* @api public
*/
EventEmitter.prototype.once = function (name, fn) {
var self = this;
function on () {
self.removeListener(name, on);
fn.apply(this, arguments);
};
on.listener = fn;
this.on(name, on);
return this;
};
/**
* Removes a listener.
*
* @api public
*/
EventEmitter.prototype.removeListener = function (name, fn) {
if (this.$events && this.$events[name]) {
var list = this.$events[name];
if (isArray(list)) {
var pos = -1;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
pos = i;
break;
}
}
if (pos < 0) {
return this;
}
list.splice(pos, 1);
if (!list.length) {
delete this.$events[name];
}
} else if (list === fn || (list.listener && list.listener === fn)) {
delete this.$events[name];
}
}
return this;
};
/**
* Removes all listeners for an event.
*
* @api public
*/
EventEmitter.prototype.removeAllListeners = function (name) {
if (name === undefined) {
this.$events = {};
return this;
}
if (this.$events && this.$events[name]) {
this.$events[name] = null;
}
return this;
};
/**
* Gets all listeners for a certain event.
*
* @api public
*/
EventEmitter.prototype.listeners = function (name) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = [];
}
if (!isArray(this.$events[name])) {
this.$events[name] = [this.$events[name]];
}
return this.$events[name];
};
/**
* Emits an event.
*
* @api public
*/
EventEmitter.prototype.emit = function (name) {
if (!this.$events) {
return false;
}
var handler = this.$events[name];
if (!handler) {
return false;
}
var args = [].slice.call(arguments, 1);
if ('function' == typeof handler) {
handler.apply(this, args);
} else if (isArray(handler)) {
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
} else {
return false;
}
return true;
};
}); // module: browser/events.js
require.register("browser/fs.js", function(module, exports, require){
}); // module: browser/fs.js
require.register("browser/path.js", function(module, exports, require){
}); // module: browser/path.js
require.register("browser/progress.js", function(module, exports, require){
/**
* Expose `Progress`.
*/
module.exports = Progress;
/**
* Initialize a new `Progress` indicator.
*/
function Progress() {
this.percent = 0;
this.size(0);
this.fontSize(11);
this.font('helvetica, arial, sans-serif');
}
/**
* Set progress size to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.size = function(n){
this._size = n;
return this;
};
/**
* Set text to `str`.
*
* @param {String} str
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.text = function(str){
this._text = str;
return this;
};
/**
* Set font size to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.fontSize = function(n){
this._fontSize = n;
return this;
};
/**
* Set font `family`.
*
* @param {String} family
* @return {Progress} for chaining
*/
Progress.prototype.font = function(family){
this._font = family;
return this;
};
/**
* Update percentage to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
*/
Progress.prototype.update = function(n){
this.percent = n;
return this;
};
/**
* Draw on `ctx`.
*
* @param {CanvasRenderingContext2d} ctx
* @return {Progress} for chaining
*/
Progress.prototype.draw = function(ctx){
try {
var percent = Math.min(this.percent, 100)
, size = this._size
, half = size / 2
, x = half
, y = half
, rad = half - 1
, fontSize = this._fontSize;
ctx.font = fontSize + 'px ' + this._font;
var angle = Math.PI * 2 * (percent / 100);
ctx.clearRect(0, 0, size, size);
// outer circle
ctx.strokeStyle = '#9f9f9f';
ctx.beginPath();
ctx.arc(x, y, rad, 0, angle, false);
ctx.stroke();
// inner circle
ctx.strokeStyle = '#eee';
ctx.beginPath();
ctx.arc(x, y, rad - 1, 0, angle, true);
ctx.stroke();
// text
var text = this._text || (percent | 0) + '%'
, w = ctx.measureText(text).width;
ctx.fillText(
text
, x - w / 2 + 1
, y + fontSize / 2 - 1);
} catch (ex) {} //don't fail if we can't render progress
return this;
};
}); // module: browser/progress.js
require.register("browser/tty.js", function(module, exports, require){
exports.isatty = function(){
return true;
};
exports.getWindowSize = function(){
if ('innerHeight' in global) {
return [global.innerHeight, global.innerWidth];
} else {
// In a Web Worker, the DOM Window is not available.
return [640, 480];
}
};
}); // module: browser/tty.js
require.register("context.js", function(module, exports, require){
/**
* Expose `Context`.
*/
module.exports = Context;
/**
* Initialize a new `Context`.
*
* @api private
*/
function Context(){}
/**
* Set or get the context `Runnable` to `runnable`.
*
* @param {Runnable} runnable
* @return {Context}
* @api private
*/
Context.prototype.runnable = function(runnable){
if (0 == arguments.length) return this._runnable;
this.test = this._runnable = runnable;
return this;
};
/**
* Set test timeout `ms`.
*
* @param {Number} ms
* @return {Context} self
* @api private
*/
Context.prototype.timeout = function(ms){
this.runnable().timeout(ms);
return this;
};
/**
* Set test slowness threshold `ms`.
*
* @param {Number} ms
* @return {Context} self
* @api private
*/
Context.prototype.slow = function(ms){
this.runnable().slow(ms);
return this;
};
/**
* Inspect the context void of `._runnable`.
*
* @return {String}
* @api private
*/
Context.prototype.inspect = function(){
return JSON.stringify(this, function(key, val){
if ('_runnable' == key) return;
if ('test' == key) return;
return val;
}, 2);
};
}); // module: context.js
require.register("hook.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Runnable = require('./runnable');
/**
* Expose `Hook`.
*/
module.exports = Hook;
/**
* Initialize a new `Hook` with the given `title` and callback `fn`.
*
* @param {String} title
* @param {Function} fn
* @api private
*/
function Hook(title, fn) {
Runnable.call(this, title, fn);
this.type = 'hook';
}
/**
* Inherit from `Runnable.prototype`.
*/
function F(){};
F.prototype = Runnable.prototype;
Hook.prototype = new F;
Hook.prototype.constructor = Hook;
/**
* Get or set the test `err`.
*
* @param {Error} err
* @return {Error}
* @api public
*/
Hook.prototype.error = function(err){
if (0 == arguments.length) {
var err = this._error;
this._error = null;
return err;
}
this._error = err;
};
}); // module: hook.js
require.register("interfaces/bdd.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test')
, utils = require('../utils');
/**
* BDD-style interface:
*
* describe('Array', function(){
* describe('#indexOf()', function(){
* it('should return -1 when not present', function(){
*
* });
*
* it('should return the index when present', function(){
*
* });
* });
* });
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('pre-require', function(context, file, mocha){
/**
* Execute before running tests.
*/
context.before = function(name, fn){
suites[0].beforeAll(name, fn);
};
/**
* Execute after running tests.
*/
context.after = function(name, fn){
suites[0].afterAll(name, fn);
};
/**
* Execute before each test case.
*/
context.beforeEach = function(name, fn){
suites[0].beforeEach(name, fn);
};
/**
* Execute after each test case.
*/
context.afterEach = function(name, fn){
suites[0].afterEach(name, fn);
};
/**
* Describe a "suite" with the given `title`
* and callback `fn` containing nested suites
* and/or tests.
*/
context.describe = context.context = function(title, fn){
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
};
/**
* Pending describe.
*/
context.xdescribe =
context.xcontext =
context.describe.skip = function(title, fn){
var suite = Suite.create(suites[0], title);
suite.pending = true;
suites.unshift(suite);
fn.call(suite);
suites.shift();
};
/**
* Exclusive suite.
*/
context.describe.only = function(title, fn){
var suite = context.describe(title, fn);
mocha.grep(suite.fullTitle());
return suite;
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.it = context.specify = function(title, fn){
var suite = suites[0];
if (suite.pending) var fn = null;
var test = new Test(title, fn);
suite.addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.it.only = function(title, fn){
var test = context.it(title, fn);
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
mocha.grep(new RegExp(reString));
return test;
};
/**
* Pending test case.
*/
context.xit =
context.xspecify =
context.it.skip = function(title){
context.it(title);
};
});
};
}); // module: interfaces/bdd.js
require.register("interfaces/exports.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test');
/**
* TDD-style interface:
*
* exports.Array = {
* '#indexOf()': {
* 'should return -1 when the value is not present': function(){
*
* },
*
* 'should return the correct index when the value is present': function(){
*
* }
* }
* };
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('require', visit);
function visit(obj) {
var suite;
for (var key in obj) {
if ('function' == typeof obj[key]) {
var fn = obj[key];
switch (key) {
case 'before':
suites[0].beforeAll(fn);
break;
case 'after':
suites[0].afterAll(fn);
break;
case 'beforeEach':
suites[0].beforeEach(fn);
break;
case 'afterEach':
suites[0].afterEach(fn);
break;
default:
suites[0].addTest(new Test(key, fn));
}
} else {
var suite = Suite.create(suites[0], key);
suites.unshift(suite);
visit(obj[key]);
suites.shift();
}
}
}
};
}); // module: interfaces/exports.js
require.register("interfaces/index.js", function(module, exports, require){
exports.bdd = require('./bdd');
exports.tdd = require('./tdd');
exports.qunit = require('./qunit');
exports.exports = require('./exports');
}); // module: interfaces/index.js
require.register("interfaces/qunit.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test')
, utils = require('../utils');
/**
* QUnit-style interface:
*
* suite('Array');
*
* test('#length', function(){
* var arr = [1,2,3];
* ok(arr.length == 3);
* });
*
* test('#indexOf()', function(){
* var arr = [1,2,3];
* ok(arr.indexOf(1) == 0);
* ok(arr.indexOf(2) == 1);
* ok(arr.indexOf(3) == 2);
* });
*
* suite('String');
*
* test('#length', function(){
* ok('foo'.length == 3);
* });
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('pre-require', function(context, file, mocha){
/**
* Execute before running tests.
*/
context.before = function(name, fn){
suites[0].beforeAll(name, fn);
};
/**
* Execute after running tests.
*/
context.after = function(name, fn){
suites[0].afterAll(name, fn);
};
/**
* Execute before each test case.
*/
context.beforeEach = function(name, fn){
suites[0].beforeEach(name, fn);
};
/**
* Execute after each test case.
*/
context.afterEach = function(name, fn){
suites[0].afterEach(name, fn);
};
/**
* Describe a "suite" with the given `title`.
*/
context.suite = function(title){
if (suites.length > 1) suites.shift();
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
return suite;
};
/**
* Exclusive test-case.
*/
context.suite.only = function(title, fn){
var suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.test = function(title, fn){
var test = new Test(title, fn);
suites[0].addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.test.only = function(title, fn){
var test = context.test(title, fn);
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
mocha.grep(new RegExp(reString));
};
/**
* Pending test case.
*/
context.test.skip = function(title){
context.test(title);
};
});
};
}); // module: interfaces/qunit.js
require.register("interfaces/tdd.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test')
, utils = require('../utils');;
/**
* TDD-style interface:
*
* suite('Array', function(){
* suite('#indexOf()', function(){
* suiteSetup(function(){
*
* });
*
* test('should return -1 when not present', function(){
*
* });
*
* test('should return the index when present', function(){
*
* });
*
* suiteTeardown(function(){
*
* });
* });
* });
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('pre-require', function(context, file, mocha){
/**
* Execute before each test case.
*/
context.setup = function(name, fn){
suites[0].beforeEach(name, fn);
};
/**
* Execute after each test case.
*/
context.teardown = function(name, fn){
suites[0].afterEach(name, fn);
};
/**
* Execute before the suite.
*/
context.suiteSetup = function(name, fn){
suites[0].beforeAll(name, fn);
};
/**
* Execute after the suite.
*/
context.suiteTeardown = function(name, fn){
suites[0].afterAll(name, fn);
};
/**
* Describe a "suite" with the given `title`
* and callback `fn` containing nested suites
* and/or tests.
*/
context.suite = function(title, fn){
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
};
/**
* Pending suite.
*/
context.suite.skip = function(title, fn) {
var suite = Suite.create(suites[0], title);
suite.pending = true;
suites.unshift(suite);
fn.call(suite);
suites.shift();
};
/**
* Exclusive test-case.
*/
context.suite.only = function(title, fn){
var suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.test = function(title, fn){
var suite = suites[0];
if (suite.pending) var fn = null;
var test = new Test(title, fn);
suite.addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.test.only = function(title, fn){
var test = context.test(title, fn);
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
mocha.grep(new RegExp(reString));
};
/**
* Pending test case.
*/
context.test.skip = function(title){
context.test(title);
};
});
};
}); // module: interfaces/tdd.js
require.register("mocha.js", function(module, exports, require){
/*!
* mocha
* Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var path = require('browser/path')
, utils = require('./utils');
/**
* Expose `Mocha`.
*/
exports = module.exports = Mocha;
/**
* Expose internals.
*/
exports.utils = utils;
exports.interfaces = require('./interfaces');
exports.reporters = require('./reporters');
exports.Runnable = require('./runnable');
exports.Context = require('./context');
exports.Runner = require('./runner');
exports.Suite = require('./suite');
exports.Hook = require('./hook');
exports.Test = require('./test');
/**
* Return image `name` path.
*
* @param {String} name
* @return {String}
* @api private
*/
function image(name) {
return __dirname + '/../images/' + name + '.png';
}
/**
* Setup mocha with `options`.
*
* Options:
*
* - `ui` name "bdd", "tdd", "exports" etc
* - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
* - `globals` array of accepted globals
* - `timeout` timeout in milliseconds
* - `bail` bail on the first test failure
* - `slow` milliseconds to wait before considering a test slow
* - `ignoreLeaks` ignore global leaks
* - `grep` string or regexp to filter tests with
*
* @param {Object} options
* @api public
*/
function Mocha(options) {
options = options || {};
this.files = [];
this.options = options;
this.grep(options.grep);
this.suite = new exports.Suite('', new exports.Context);
this.ui(options.ui);
this.bail(options.bail);
this.reporter(options.reporter);
if (null != options.timeout) this.timeout(options.timeout);
this.useColors(options.useColors)
if (options.slow) this.slow(options.slow);
this.suite.on('pre-require', function (context) {
exports.afterEach = context.afterEach || context.teardown;
exports.after = context.after || context.suiteTeardown;
exports.beforeEach = context.beforeEach || context.setup;
exports.before = context.before || context.suiteSetup;
exports.describe = context.describe || context.suite;
exports.it = context.it || context.test;
exports.setup = context.setup || context.beforeEach;
exports.suiteSetup = context.suiteSetup || context.before;
exports.suiteTeardown = context.suiteTeardown || context.after;
exports.suite = context.suite || context.describe;
exports.teardown = context.teardown || context.afterEach;
exports.test = context.test || context.it;
});
}
/**
* Enable or disable bailing on the first failure.
*
* @param {Boolean} [bail]
* @api public
*/
Mocha.prototype.bail = function(bail){
if (0 == arguments.length) bail = true;
this.suite.bail(bail);
return this;
};
/**
* Add test `file`.
*
* @param {String} file
* @api public
*/
Mocha.prototype.addFile = function(file){
this.files.push(file);
return this;
};
/**
* Set reporter to `reporter`, defaults to "dot".
*
* @param {String|Function} reporter name or constructor
* @api public
*/
Mocha.prototype.reporter = function(reporter){
if ('function' == typeof reporter) {
this._reporter = reporter;
} else {
reporter = reporter || 'dot';
var _reporter;
try { _reporter = require('./reporters/' + reporter); } catch (err) {};
if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
if (!_reporter && reporter === 'teamcity')
console.warn('The Teamcity reporter was moved to a package named ' +
'mocha-teamcity-reporter ' +
'(https://npmjs.org/package/mocha-teamcity-reporter).');
if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
this._reporter = _reporter;
}
return this;
};
/**
* Set test UI `name`, defaults to "bdd".
*
* @param {String} bdd
* @api public
*/
Mocha.prototype.ui = function(name){
name = name || 'bdd';
this._ui = exports.interfaces[name];
if (!this._ui) try { this._ui = require(name); } catch (err) {};
if (!this._ui) throw new Error('invalid interface "' + name + '"');
this._ui = this._ui(this.suite);
return this;
};
/**
* Load registered files.
*
* @api private
*/
Mocha.prototype.loadFiles = function(fn){
var self = this;
var suite = this.suite;
var pending = this.files.length;
this.files.forEach(function(file){
file = path.resolve(file);
suite.emit('pre-require', global, file, self);
suite.emit('require', require(file), file, self);
suite.emit('post-require', global, file, self);
--pending || (fn && fn());
});
};
/**
* Enable growl support.
*
* @api private
*/
Mocha.prototype._growl = function(runner, reporter) {
var notify = require('growl');
runner.on('end', function(){
var stats = reporter.stats;
if (stats.failures) {
var msg = stats.failures + ' of ' + runner.total + ' tests failed';
notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
} else {
notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
name: 'mocha'
, title: 'Passed'
, image: image('ok')
});
}
});
};
/**
* Add regexp to grep, if `re` is a string it is escaped.
*
* @param {RegExp|String} re
* @return {Mocha}
* @api public
*/
Mocha.prototype.grep = function(re){
this.options.grep = 'string' == typeof re
? new RegExp(utils.escapeRegexp(re))
: re;
return this;
};
/**
* Invert `.grep()` matches.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.invert = function(){
this.options.invert = true;
return this;
};
/**
* Ignore global leaks.
*
* @param {Boolean} ignore
* @return {Mocha}
* @api public
*/
Mocha.prototype.ignoreLeaks = function(ignore){
this.options.ignoreLeaks = !!ignore;
return this;
};
/**
* Enable global leak checking.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.checkLeaks = function(){
this.options.ignoreLeaks = false;
return this;
};
/**
* Enable growl support.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.growl = function(){
this.options.growl = true;
return this;
};
/**
* Ignore `globals` array or string.
*
* @param {Array|String} globals
* @return {Mocha}
* @api public
*/
Mocha.prototype.globals = function(globals){
this.options.globals = (this.options.globals || []).concat(globals);
return this;
};
/**
* Emit color output.
*
* @param {Boolean} colors
* @return {Mocha}
* @api public
*/
Mocha.prototype.useColors = function(colors){
this.options.useColors = arguments.length && colors != undefined
? colors
: true;
return this;
};
/**
* Use inline diffs rather than +/-.
*
* @param {Boolean} inlineDiffs
* @return {Mocha}
* @api public
*/
Mocha.prototype.useInlineDiffs = function(inlineDiffs) {
this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined
? inlineDiffs
: false;
return this;
};
/**
* Set the timeout in milliseconds.
*
* @param {Number} timeout
* @return {Mocha}
* @api public
*/
Mocha.prototype.timeout = function(timeout){
this.suite.timeout(timeout);
return this;
};
/**
* Set slowness threshold in milliseconds.
*
* @param {Number} slow
* @return {Mocha}
* @api public
*/
Mocha.prototype.slow = function(slow){
this.suite.slow(slow);
return this;
};
/**
* Makes all tests async (accepting a callback)
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.asyncOnly = function(){
this.options.asyncOnly = true;
return this;
};
/**
* Run tests and invoke `fn()` when complete.
*
* @param {Function} fn
* @return {Runner}
* @api public
*/
Mocha.prototype.run = function(fn){
if (this.files.length) this.loadFiles();
var suite = this.suite;
var options = this.options;
options.files = this.files;
var runner = new exports.Runner(suite);
var reporter = new this._reporter(runner, options);
runner.ignoreLeaks = false !== options.ignoreLeaks;
runner.asyncOnly = options.asyncOnly;
if (options.grep) runner.grep(options.grep, options.invert);
if (options.globals) runner.globals(options.globals);
if (options.growl) this._growl(runner, reporter);
exports.reporters.Base.useColors = options.useColors;
exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
return runner.run(fn);
};
}); // module: mocha.js
require.register("ms.js", function(module, exports, require){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @return {String|Number}
* @api public
*/
module.exports = function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
return options.long ? longFormat(val) : shortFormat(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
if (!match) return;
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 's':
return n * s;
case 'ms':
return n;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function shortFormat(ms) {
if (ms >= d) return Math.round(ms / d) + 'd';
if (ms >= h) return Math.round(ms / h) + 'h';
if (ms >= m) return Math.round(ms / m) + 'm';
if (ms >= s) return Math.round(ms / s) + 's';
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function longFormat(ms) {
return plural(ms, d, 'day')
|| plural(ms, h, 'hour')
|| plural(ms, m, 'minute')
|| plural(ms, s, 'second')
|| ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) return;
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
return Math.ceil(ms / n) + ' ' + name + 's';
}
}); // module: ms.js
require.register("reporters/base.js", function(module, exports, require){
/**
* Module dependencies.
*/
var tty = require('browser/tty')
, diff = require('browser/diff')
, ms = require('../ms')
, utils = require('../utils');
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
var Date = global.Date
, setTimeout = global.setTimeout
, setInterval = global.setInterval
, clearTimeout = global.clearTimeout
, clearInterval = global.clearInterval;
/**
* Check if both stdio streams are associated with a tty.
*/
var isatty = tty.isatty(1) && tty.isatty(2);
/**
* Expose `Base`.
*/
exports = module.exports = Base;
/**
* Enable coloring by default.
*/
exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined);
/**
* Inline diffs instead of +/-
*/
exports.inlineDiffs = false;
/**
* Default color map.
*/
exports.colors = {
'pass': 90
, 'fail': 31
, 'bright pass': 92
, 'bright fail': 91
, 'bright yellow': 93
, 'pending': 36
, 'suite': 0
, 'error title': 0
, 'error message': 31
, 'error stack': 90
, 'checkmark': 32
, 'fast': 90
, 'medium': 33
, 'slow': 31
, 'green': 32
, 'light': 90
, 'diff gutter': 90
, 'diff added': 42
, 'diff removed': 41
};
/**
* Default symbol map.
*/
exports.symbols = {
ok: '✓',
err: '✖',
dot: '․'
};
// With node.js on Windows: use symbols available in terminal default fonts
if ('win32' == process.platform) {
exports.symbols.ok = '\u221A';
exports.symbols.err = '\u00D7';
exports.symbols.dot = '.';
}
/**
* Color `str` with the given `type`,
* allowing colors to be disabled,
* as well as user-defined color
* schemes.
*
* @param {String} type
* @param {String} str
* @return {String}
* @api private
*/
var color = exports.color = function(type, str) {
if (!exports.useColors) return str;
return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
};
/**
* Expose term window size, with some
* defaults for when stderr is not a tty.
*/
exports.window = {
width: isatty
? process.stdout.getWindowSize
? process.stdout.getWindowSize(1)[0]
: tty.getWindowSize()[1]
: 75
};
/**
* Expose some basic cursor interactions
* that are common among reporters.
*/
exports.cursor = {
hide: function(){
isatty && process.stdout.write('\u001b[?25l');
},
show: function(){
isatty && process.stdout.write('\u001b[?25h');
},
deleteLine: function(){
isatty && process.stdout.write('\u001b[2K');
},
beginningOfLine: function(){
isatty && process.stdout.write('\u001b[0G');
},
CR: function(){
if (isatty) {
exports.cursor.deleteLine();
exports.cursor.beginningOfLine();
} else {
process.stdout.write('\r');
}
}
};
/**
* Outut the given `failures` as a list.
*
* @param {Array} failures
* @api public
*/
exports.list = function(failures){
console.error();
failures.forEach(function(test, i){
// format
var fmt = color('error title', ' %s) %s:\n')
+ color('error message', ' %s')
+ color('error stack', '\n%s\n');
// msg
var err = test.err
, message = err.message || ''
, stack = err.stack || message
, index = stack.indexOf(message) + message.length
, msg = stack.slice(0, index)
, actual = err.actual
, expected = err.expected
, escape = true;
// uncaught
if (err.uncaught) {
msg = 'Uncaught ' + msg;
}
// explicitly show diff
if (err.showDiff && sameType(actual, expected)) {
escape = false;
err.actual = actual = stringify(canonicalize(actual));
err.expected = expected = stringify(canonicalize(expected));
}
// actual / expected diff
if ('string' == typeof actual && 'string' == typeof expected) {
fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
var match = message.match(/^([^:]+): expected/);
msg = '\n ' + color('error message', match ? match[1] : msg);
if (exports.inlineDiffs) {
msg += inlineDiff(err, escape);
} else {
msg += unifiedDiff(err, escape);
}
}
// indent stack trace without msg
stack = stack.slice(index ? index + 1 : index)
.replace(/^/gm, ' ');
console.error(fmt, (i + 1), test.fullTitle(), msg, stack);
});
};
/**
* Initialize a new `Base` reporter.
*
* All other reporters generally
* inherit from this reporter, providing
* stats such as test duration, number
* of tests passed / failed etc.
*
* @param {Runner} runner
* @api public
*/
function Base(runner) {
var self = this
, stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
, failures = this.failures = [];
if (!runner) return;
this.runner = runner;
runner.stats = stats;
runner.on('start', function(){
stats.start = new Date;
});
runner.on('suite', function(suite){
stats.suites = stats.suites || 0;
suite.root || stats.suites++;
});
runner.on('test end', function(test){
stats.tests = stats.tests || 0;
stats.tests++;
});
runner.on('pass', function(test){
stats.passes = stats.passes || 0;
var medium = test.slow() / 2;
test.speed = test.duration > test.slow()
? 'slow'
: test.duration > medium
? 'medium'
: 'fast';
stats.passes++;
});
runner.on('fail', function(test, err){
stats.failures = stats.failures || 0;
stats.failures++;
test.err = err;
failures.push(test);
});
runner.on('end', function(){
stats.end = new Date;
stats.duration = new Date - stats.start;
});
runner.on('pending', function(){
stats.pending++;
});
}
/**
* Output common epilogue used by many of
* the bundled reporters.
*
* @api public
*/
Base.prototype.epilogue = function(){
var stats = this.stats;
var tests;
var fmt;
console.log();
// passes
fmt = color('bright pass', ' ')
+ color('green', ' %d passing')
+ color('light', ' (%s)');
console.log(fmt,
stats.passes || 0,
ms(stats.duration));
// pending
if (stats.pending) {
fmt = color('pending', ' ')
+ color('pending', ' %d pending');
console.log(fmt, stats.pending);
}
// failures
if (stats.failures) {
fmt = color('fail', ' %d failing');
console.error(fmt,
stats.failures);
Base.list(this.failures);
console.error();
}
console.log();
};
/**
* Pad the given `str` to `len`.
*
* @param {String} str
* @param {String} len
* @return {String}
* @api private
*/
function pad(str, len) {
str = String(str);
return Array(len - str.length + 1).join(' ') + str;
}
/**
* Returns an inline diff between 2 strings with coloured ANSI output
*
* @param {Error} Error with actual/expected
* @return {String} Diff
* @api private
*/
function inlineDiff(err, escape) {
var msg = errorDiff(err, 'WordsWithSpace', escape);
// linenos
var lines = msg.split('\n');
if (lines.length > 4) {
var width = String(lines.length).length;
msg = lines.map(function(str, i){
return pad(++i, width) + ' |' + ' ' + str;
}).join('\n');
}
// legend
msg = '\n'
+ color('diff removed', 'actual')
+ ' '
+ color('diff added', 'expected')
+ '\n\n'
+ msg
+ '\n';
// indent
msg = msg.replace(/^/gm, ' ');
return msg;
}
/**
* Returns a unified diff between 2 strings
*
* @param {Error} Error with actual/expected
* @return {String} Diff
* @api private
*/
function unifiedDiff(err, escape) {
var indent = ' ';
function cleanUp(line) {
if (escape) {
line = escapeInvisibles(line);
}
if (line[0] === '+') return indent + colorLines('diff added', line);
if (line[0] === '-') return indent + colorLines('diff removed', line);
if (line.match(/\@\@/)) return null;
if (line.match(/\\ No newline/)) return null;
else return indent + line;
}
function notBlank(line) {
return line != null;
}
msg = diff.createPatch('string', err.actual, err.expected);
var lines = msg.split('\n').splice(4);
return '\n '
+ colorLines('diff added', '+ expected') + ' '
+ colorLines('diff removed', '- actual')
+ '\n\n'
+ lines.map(cleanUp).filter(notBlank).join('\n');
}
/**
* Return a character diff for `err`.
*
* @param {Error} err
* @return {String}
* @api private
*/
function errorDiff(err, type, escape) {
var actual = escape ? escapeInvisibles(err.actual) : err.actual;
var expected = escape ? escapeInvisibles(err.expected) : err.expected;
return diff['diff' + type](actual, expected).map(function(str){
if (str.added) return colorLines('diff added', str.value);
if (str.removed) return colorLines('diff removed', str.value);
return str.value;
}).join('');
}
/**
* Returns a string with all invisible characters in plain text
*
* @param {String} line
* @return {String}
* @api private
*/
function escapeInvisibles(line) {
return line.replace(/\t/g, '<tab>')
.replace(/\r/g, '<CR>')
.replace(/\n/g, '<LF>\n');
}
/**
* Color lines for `str`, using the color `name`.
*
* @param {String} name
* @param {String} str
* @return {String}
* @api private
*/
function colorLines(name, str) {
return str.split('\n').map(function(str){
return color(name, str);
}).join('\n');
}
/**
* Stringify `obj`.
*
* @param {Object} obj
* @return {String}
* @api private
*/
function stringify(obj) {
if (obj instanceof RegExp) return obj.toString();
return JSON.stringify(obj, null, 2);
}
/**
* Return a new object that has the keys in sorted order.
* @param {Object} obj
* @return {Object}
* @api private
*/
function canonicalize(obj, stack) {
stack = stack || [];
if (utils.indexOf(stack, obj) !== -1) return obj;
var canonicalizedObj;
if ('[object Array]' == {}.toString.call(obj)) {
stack.push(obj);
canonicalizedObj = utils.map(obj, function(item) {
return canonicalize(item, stack);
});
stack.pop();
} else if (typeof obj === 'object' && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
utils.forEach(utils.keys(obj).sort(), function(key) {
canonicalizedObj[key] = canonicalize(obj[key], stack);
});
stack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
/**
* Check that a / b have the same type.
*
* @param {Object} a
* @param {Object} b
* @return {Boolean}
* @api private
*/
function sameType(a, b) {
a = Object.prototype.toString.call(a);
b = Object.prototype.toString.call(b);
return a == b;
}
}); // module: reporters/base.js
require.register("reporters/doc.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, utils = require('../utils');
/**
* Expose `Doc`.
*/
exports = module.exports = Doc;
/**
* Initialize a new `Doc` reporter.
*
* @param {Runner} runner
* @api public
*/
function Doc(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, total = runner.total
, indents = 2;
function indent() {
return Array(indents).join(' ');
}
runner.on('suite', function(suite){
if (suite.root) return;
++indents;
console.log('%s<section class="suite">', indent());
++indents;
console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
console.log('%s<dl>', indent());
});
runner.on('suite end', function(suite){
if (suite.root) return;
console.log('%s</dl>', indent());
--indents;
console.log('%s</section>', indent());
--indents;
});
runner.on('pass', function(test){
console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
var code = utils.escape(utils.clean(test.fn.toString()));
console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
});
}
}); // module: reporters/doc.js
require.register("reporters/dot.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, color = Base.color;
/**
* Expose `Dot`.
*/
exports = module.exports = Dot;
/**
* Initialize a new `Dot` matrix test reporter.
*
* @param {Runner} runner
* @api public
*/
function Dot(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, width = Base.window.width * .75 | 0
, n = 0;
runner.on('start', function(){
process.stdout.write('\n ');
});
runner.on('pending', function(test){
process.stdout.write(color('pending', Base.symbols.dot));
});
runner.on('pass', function(test){
if (++n % width == 0) process.stdout.write('\n ');
if ('slow' == test.speed) {
process.stdout.write(color('bright yellow', Base.symbols.dot));
} else {
process.stdout.write(color(test.speed, Base.symbols.dot));
}
});
runner.on('fail', function(test, err){
if (++n % width == 0) process.stdout.write('\n ');
process.stdout.write(color('fail', Base.symbols.dot));
});
runner.on('end', function(){
console.log();
self.epilogue();
});
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
Dot.prototype = new F;
Dot.prototype.constructor = Dot;
}); // module: reporters/dot.js
require.register("reporters/html-cov.js", function(module, exports, require){
/**
* Module dependencies.
*/
var JSONCov = require('./json-cov')
, fs = require('browser/fs');
/**
* Expose `HTMLCov`.
*/
exports = module.exports = HTMLCov;
/**
* Initialize a new `JsCoverage` reporter.
*
* @param {Runner} runner
* @api public
*/
function HTMLCov(runner) {
var jade = require('jade')
, file = __dirname + '/templates/coverage.jade'
, str = fs.readFileSync(file, 'utf8')
, fn = jade.compile(str, { filename: file })
, self = this;
JSONCov.call(this, runner, false);
runner.on('end', function(){
process.stdout.write(fn({
cov: self.cov
, coverageClass: coverageClass
}));
});
}
/**
* Return coverage class for `n`.
*
* @return {String}
* @api private
*/
function coverageClass(n) {
if (n >= 75) return 'high';
if (n >= 50) return 'medium';
if (n >= 25) return 'low';
return 'terrible';
}
}); // module: reporters/html-cov.js
require.register("reporters/html.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, utils = require('../utils')
, Progress = require('../browser/progress')
, escape = utils.escape;
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
var Date = global.Date
, setTimeout = global.setTimeout
, setInterval = global.setInterval
, clearTimeout = global.clearTimeout
, clearInterval = global.clearInterval;
/**
* Expose `HTML`.
*/
exports = module.exports = HTML;
/**
* Stats template.
*/
var statsTemplate = '<ul id="mocha-stats">'
+ '<li class="progress"><canvas width="40" height="40"></canvas></li>'
+ '<li class="passes"><a href="#">passes:</a> <em>0</em></li>'
+ '<li class="failures"><a href="#">failures:</a> <em>0</em></li>'
+ '<li class="duration">duration: <em>0</em>s</li>'
+ '</ul>';
/**
* Initialize a new `HTML` reporter.
*
* @param {Runner} runner
* @api public
*/
function HTML(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, total = runner.total
, stat = fragment(statsTemplate)
, items = stat.getElementsByTagName('li')
, passes = items[1].getElementsByTagName('em')[0]
, passesLink = items[1].getElementsByTagName('a')[0]
, failures = items[2].getElementsByTagName('em')[0]
, failuresLink = items[2].getElementsByTagName('a')[0]
, duration = items[3].getElementsByTagName('em')[0]
, canvas = stat.getElementsByTagName('canvas')[0]
, report = fragment('<ul id="mocha-report"></ul>')
, stack = [report]
, progress
, ctx
, root = document.getElementById('mocha');
if (canvas.getContext) {
var ratio = window.devicePixelRatio || 1;
canvas.style.width = canvas.width;
canvas.style.height = canvas.height;
canvas.width *= ratio;
canvas.height *= ratio;
ctx = canvas.getContext('2d');
ctx.scale(ratio, ratio);
progress = new Progress;
}
if (!root) return error('#mocha div missing, add it to your document');
// pass toggle
on(passesLink, 'click', function(){
unhide();
var name = /pass/.test(report.className) ? '' : ' pass';
report.className = report.className.replace(/fail|pass/g, '') + name;
if (report.className.trim()) hideSuitesWithout('test pass');
});
// failure toggle
on(failuresLink, 'click', function(){
unhide();
var name = /fail/.test(report.className) ? '' : ' fail';
report.className = report.className.replace(/fail|pass/g, '') + name;
if (report.className.trim()) hideSuitesWithout('test fail');
});
root.appendChild(stat);
root.appendChild(report);
if (progress) progress.size(40);
runner.on('suite', function(suite){
if (suite.root) return;
// suite
var url = self.suiteURL(suite);
var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
// container
stack[0].appendChild(el);
stack.unshift(document.createElement('ul'));
el.appendChild(stack[0]);
});
runner.on('suite end', function(suite){
if (suite.root) return;
stack.shift();
});
runner.on('fail', function(test, err){
if ('hook' == test.type) runner.emit('test end', test);
});
runner.on('test end', function(test){
// TODO: add to stats
var percent = stats.tests / this.total * 100 | 0;
if (progress) progress.update(percent).draw(ctx);
// update stats
var ms = new Date - stats.start;
text(passes, stats.passes);
text(failures, stats.failures);
text(duration, (ms / 1000).toFixed(2));
// test
if ('passed' == test.state) {
var url = self.testURL(test);
var el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%s" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url);
} else if (test.pending) {
var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
} else {
var el = fragment('<li class="test fail"><h2>%e <a href="?grep=%e" class="replay">‣</a></h2></li>', test.title, encodeURIComponent(test.fullTitle()));
var str = test.err.stack || test.err.toString();
// FF / Opera do not add the message
if (!~str.indexOf(test.err.message)) {
str = test.err.message + '\n' + str;
}
// <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
// check for the result of the stringifying.
if ('[object Error]' == str) str = test.err.message;
// Safari doesn't give you a stack. Let's at least provide a source line.
if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) {
str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
}
el.appendChild(fragment('<pre class="error">%e</pre>', str));
}
// toggle code
// TODO: defer
if (!test.pending) {
var h2 = el.getElementsByTagName('h2')[0];
on(h2, 'click', function(){
pre.style.display = 'none' == pre.style.display
? 'block'
: 'none';
});
var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
el.appendChild(pre);
pre.style.display = 'none';
}
// Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
if (stack[0]) stack[0].appendChild(el);
});
}
/**
* Provide suite URL
*
* @param {Object} [suite]
*/
HTML.prototype.suiteURL = function(suite){
return '?grep=' + encodeURIComponent(suite.fullTitle());
};
/**
* Provide test URL
*
* @param {Object} [test]
*/
HTML.prototype.testURL = function(test){
return '?grep=' + encodeURIComponent(test.fullTitle());
};
/**
* Display error `msg`.
*/
function error(msg) {
document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
}
/**
* Return a DOM fragment from `html`.
*/
function fragment(html) {
var args = arguments
, div = document.createElement('div')
, i = 1;
div.innerHTML = html.replace(/%([se])/g, function(_, type){
switch (type) {
case 's': return String(args[i++]);
case 'e': return escape(args[i++]);
}
});
return div.firstChild;
}
/**
* Check for suites that do not have elements
* with `classname`, and hide them.
*/
function hideSuitesWithout(classname) {
var suites = document.getElementsByClassName('suite');
for (var i = 0; i < suites.length; i++) {
var els = suites[i].getElementsByClassName(classname);
if (0 == els.length) suites[i].className += ' hidden';
}
}
/**
* Unhide .hidden suites.
*/
function unhide() {
var els = document.getElementsByClassName('suite hidden');
for (var i = 0; i < els.length; ++i) {
els[i].className = els[i].className.replace('suite hidden', 'suite');
}
}
/**
* Set `el` text to `str`.
*/
function text(el, str) {
if (el.textContent) {
el.textContent = str;
} else {
el.innerText = str;
}
}
/**
* Listen on `event` with callback `fn`.
*/
function on(el, event, fn) {
if (el.addEventListener) {
el.addEventListener(event, fn, false);
} else {
el.attachEvent('on' + event, fn);
}
}
}); // module: reporters/html.js
require.register("reporters/index.js", function(module, exports, require){
exports.Base = require('./base');
exports.Dot = require('./dot');
exports.Doc = require('./doc');
exports.TAP = require('./tap');
exports.JSON = require('./json');
exports.HTML = require('./html');
exports.List = require('./list');
exports.Min = require('./min');
exports.Spec = require('./spec');
exports.Nyan = require('./nyan');
exports.XUnit = require('./xunit');
exports.Markdown = require('./markdown');
exports.Progress = require('./progress');
exports.Landing = require('./landing');
exports.JSONCov = require('./json-cov');
exports.HTMLCov = require('./html-cov');
exports.JSONStream = require('./json-stream');
}); // module: reporters/index.js
require.register("reporters/json-cov.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base');
/**
* Expose `JSONCov`.
*/
exports = module.exports = JSONCov;
/**
* Initialize a new `JsCoverage` reporter.
*
* @param {Runner} runner
* @param {Boolean} output
* @api public
*/
function JSONCov(runner, output) {
var self = this
, output = 1 == arguments.length ? true : output;
Base.call(this, runner);
var tests = []
, failures = []
, passes = [];
runner.on('test end', function(test){
tests.push(test);
});
runner.on('pass', function(test){
passes.push(test);
});
runner.on('fail', function(test){
failures.push(test);
});
runner.on('end', function(){
var cov = global._$jscoverage || {};
var result = self.cov = map(cov);
result.stats = self.stats;
result.tests = tests.map(clean);
result.failures = failures.map(clean);
result.passes = passes.map(clean);
if (!output) return;
process.stdout.write(JSON.stringify(result, null, 2 ));
});
}
/**
* Map jscoverage data to a JSON structure
* suitable for reporting.
*
* @param {Object} cov
* @return {Object}
* @api private
*/
function map(cov) {
var ret = {
instrumentation: 'node-jscoverage'
, sloc: 0
, hits: 0
, misses: 0
, coverage: 0
, files: []
};
for (var filename in cov) {
var data = coverage(filename, cov[filename]);
ret.files.push(data);
ret.hits += data.hits;
ret.misses += data.misses;
ret.sloc += data.sloc;
}
ret.files.sort(function(a, b) {
return a.filename.localeCompare(b.filename);
});
if (ret.sloc > 0) {
ret.coverage = (ret.hits / ret.sloc) * 100;
}
return ret;
};
/**
* Map jscoverage data for a single source file
* to a JSON structure suitable for reporting.
*
* @param {String} filename name of the source file
* @param {Object} data jscoverage coverage data
* @return {Object}
* @api private
*/
function coverage(filename, data) {
var ret = {
filename: filename,
coverage: 0,
hits: 0,
misses: 0,
sloc: 0,
source: {}
};
data.source.forEach(function(line, num){
num++;
if (data[num] === 0) {
ret.misses++;
ret.sloc++;
} else if (data[num] !== undefined) {
ret.hits++;
ret.sloc++;
}
ret.source[num] = {
source: line
, coverage: data[num] === undefined
? ''
: data[num]
};
});
ret.coverage = ret.hits / ret.sloc * 100;
return ret;
}
/**
* Return a plain-object representation of `test`
* free of cyclic properties etc.
*
* @param {Object} test
* @return {Object}
* @api private
*/
function clean(test) {
return {
title: test.title
, fullTitle: test.fullTitle()
, duration: test.duration
}
}
}); // module: reporters/json-cov.js
require.register("reporters/json-stream.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, color = Base.color;
/**
* Expose `List`.
*/
exports = module.exports = List;
/**
* Initialize a new `List` test reporter.
*
* @param {Runner} runner
* @api public
*/
function List(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, total = runner.total;
runner.on('start', function(){
console.log(JSON.stringify(['start', { total: total }]));
});
runner.on('pass', function(test){
console.log(JSON.stringify(['pass', clean(test)]));
});
runner.on('fail', function(test, err){
console.log(JSON.stringify(['fail', clean(test)]));
});
runner.on('end', function(){
process.stdout.write(JSON.stringify(['end', self.stats]));
});
}
/**
* Return a plain-object representation of `test`
* free of cyclic properties etc.
*
* @param {Object} test
* @return {Object}
* @api private
*/
function clean(test) {
return {
title: test.title
, fullTitle: test.fullTitle()
, duration: test.duration
}
}
}); // module: reporters/json-stream.js
require.register("reporters/json.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `JSON`.
*/
exports = module.exports = JSONReporter;
/**
* Initialize a new `JSON` reporter.
*
* @param {Runner} runner
* @api public
*/
function JSONReporter(runner) {
var self = this;
Base.call(this, runner);
var tests = []
, failures = []
, passes = [];
runner.on('test end', function(test){
tests.push(test);
});
runner.on('pass', function(test){
passes.push(test);
});
runner.on('fail', function(test){
failures.push(test);
});
runner.on('end', function(){
var obj = {
stats: self.stats
, tests: tests.map(clean)
, failures: failures.map(clean)
, passes: passes.map(clean)
};
process.stdout.write(JSON.stringify(obj, null, 2));
});
}
/**
* Return a plain-object representation of `test`
* free of cyclic properties etc.
*
* @param {Object} test
* @return {Object}
* @api private
*/
function clean(test) {
return {
title: test.title
, fullTitle: test.fullTitle()
, duration: test.duration
}
}
}); // module: reporters/json.js
require.register("reporters/landing.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `Landing`.
*/
exports = module.exports = Landing;
/**
* Airplane color.
*/
Base.colors.plane = 0;
/**
* Airplane crash color.
*/
Base.colors['plane crash'] = 31;
/**
* Runway color.
*/
Base.colors.runway = 90;
/**
* Initialize a new `Landing` reporter.
*
* @param {Runner} runner
* @api public
*/
function Landing(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, width = Base.window.width * .75 | 0
, total = runner.total
, stream = process.stdout
, plane = color('plane', '✈')
, crashed = -1
, n = 0;
function runway() {
var buf = Array(width).join('-');
return ' ' + color('runway', buf);
}
runner.on('start', function(){
stream.write('\n ');
cursor.hide();
});
runner.on('test end', function(test){
// check if the plane crashed
var col = -1 == crashed
? width * ++n / total | 0
: crashed;
// show the crash
if ('failed' == test.state) {
plane = color('plane crash', '✈');
crashed = col;
}
// render landing strip
stream.write('\u001b[4F\n\n');
stream.write(runway());
stream.write('\n ');
stream.write(color('runway', Array(col).join('⋅')));
stream.write(plane)
stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
stream.write(runway());
stream.write('\u001b[0m');
});
runner.on('end', function(){
cursor.show();
console.log();
self.epilogue();
});
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
Landing.prototype = new F;
Landing.prototype.constructor = Landing;
}); // module: reporters/landing.js
require.register("reporters/list.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `List`.
*/
exports = module.exports = List;
/**
* Initialize a new `List` test reporter.
*
* @param {Runner} runner
* @api public
*/
function List(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, n = 0;
runner.on('start', function(){
console.log();
});
runner.on('test', function(test){
process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
});
runner.on('pending', function(test){
var fmt = color('checkmark', ' -')
+ color('pending', ' %s');
console.log(fmt, test.fullTitle());
});
runner.on('pass', function(test){
var fmt = color('checkmark', ' '+Base.symbols.dot)
+ color('pass', ' %s: ')
+ color(test.speed, '%dms');
cursor.CR();
console.log(fmt, test.fullTitle(), test.duration);
});
runner.on('fail', function(test, err){
cursor.CR();
console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
});
runner.on('end', self.epilogue.bind(self));
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
List.prototype = new F;
List.prototype.constructor = List;
}); // module: reporters/list.js
require.register("reporters/markdown.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, utils = require('../utils');
/**
* Expose `Markdown`.
*/
exports = module.exports = Markdown;
/**
* Initialize a new `Markdown` reporter.
*
* @param {Runner} runner
* @api public
*/
function Markdown(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, level = 0
, buf = '';
function title(str) {
return Array(level).join('#') + ' ' + str;
}
function indent() {
return Array(level).join(' ');
}
function mapTOC(suite, obj) {
var ret = obj;
obj = obj[suite.title] = obj[suite.title] || { suite: suite };
suite.suites.forEach(function(suite){
mapTOC(suite, obj);
});
return ret;
}
function stringifyTOC(obj, level) {
++level;
var buf = '';
var link;
for (var key in obj) {
if ('suite' == key) continue;
if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
if (key) buf += Array(level).join(' ') + link;
buf += stringifyTOC(obj[key], level);
}
--level;
return buf;
}
function generateTOC(suite) {
var obj = mapTOC(suite, {});
return stringifyTOC(obj, 0);
}
generateTOC(runner.suite);
runner.on('suite', function(suite){
++level;
var slug = utils.slug(suite.fullTitle());
buf += '<a name="' + slug + '"></a>' + '\n';
buf += title(suite.title) + '\n';
});
runner.on('suite end', function(suite){
--level;
});
runner.on('pass', function(test){
var code = utils.clean(test.fn.toString());
buf += test.title + '.\n';
buf += '\n```js\n';
buf += code + '\n';
buf += '```\n\n';
});
runner.on('end', function(){
process.stdout.write('# TOC\n');
process.stdout.write(generateTOC(runner.suite));
process.stdout.write(buf);
});
}
}); // module: reporters/markdown.js
require.register("reporters/min.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base');
/**
* Expose `Min`.
*/
exports = module.exports = Min;
/**
* Initialize a new `Min` minimal test reporter (best used with --watch).
*
* @param {Runner} runner
* @api public
*/
function Min(runner) {
Base.call(this, runner);
runner.on('start', function(){
// clear screen
process.stdout.write('\u001b[2J');
// set cursor position
process.stdout.write('\u001b[1;3H');
});
runner.on('end', this.epilogue.bind(this));
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
Min.prototype = new F;
Min.prototype.constructor = Min;
}); // module: reporters/min.js
require.register("reporters/nyan.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, color = Base.color;
/**
* Expose `Dot`.
*/
exports = module.exports = NyanCat;
/**
* Initialize a new `Dot` matrix test reporter.
*
* @param {Runner} runner
* @api public
*/
function NyanCat(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, width = Base.window.width * .75 | 0
, rainbowColors = this.rainbowColors = self.generateColors()
, colorIndex = this.colorIndex = 0
, numerOfLines = this.numberOfLines = 4
, trajectories = this.trajectories = [[], [], [], []]
, nyanCatWidth = this.nyanCatWidth = 11
, trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
, scoreboardWidth = this.scoreboardWidth = 5
, tick = this.tick = 0
, n = 0;
runner.on('start', function(){
Base.cursor.hide();
self.draw();
});
runner.on('pending', function(test){
self.draw();
});
runner.on('pass', function(test){
self.draw();
});
runner.on('fail', function(test, err){
self.draw();
});
runner.on('end', function(){
Base.cursor.show();
for (var i = 0; i < self.numberOfLines; i++) write('\n');
self.epilogue();
});
}
/**
* Draw the nyan cat
*
* @api private
*/
NyanCat.prototype.draw = function(){
this.appendRainbow();
this.drawScoreboard();
this.drawRainbow();
this.drawNyanCat();
this.tick = !this.tick;
};
/**
* Draw the "scoreboard" showing the number
* of passes, failures and pending tests.
*
* @api private
*/
NyanCat.prototype.drawScoreboard = function(){
var stats = this.stats;
var colors = Base.colors;
function draw(color, n) {
write(' ');
write('\u001b[' + color + 'm' + n + '\u001b[0m');
write('\n');
}
draw(colors.green, stats.passes);
draw(colors.fail, stats.failures);
draw(colors.pending, stats.pending);
write('\n');
this.cursorUp(this.numberOfLines);
};
/**
* Append the rainbow.
*
* @api private
*/
NyanCat.prototype.appendRainbow = function(){
var segment = this.tick ? '_' : '-';
var rainbowified = this.rainbowify(segment);
for (var index = 0; index < this.numberOfLines; index++) {
var trajectory = this.trajectories[index];
if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift();
trajectory.push(rainbowified);
}
};
/**
* Draw the rainbow.
*
* @api private
*/
NyanCat.prototype.drawRainbow = function(){
var self = this;
this.trajectories.forEach(function(line, index) {
write('\u001b[' + self.scoreboardWidth + 'C');
write(line.join(''));
write('\n');
});
this.cursorUp(this.numberOfLines);
};
/**
* Draw the nyan cat
*
* @api private
*/
NyanCat.prototype.drawNyanCat = function() {
var self = this;
var startWidth = this.scoreboardWidth + this.trajectories[0].length;
var color = '\u001b[' + startWidth + 'C';
var padding = '';
write(color);
write('_,------,');
write('\n');
write(color);
padding = self.tick ? ' ' : ' ';
write('_|' + padding + '/\\_/\\ ');
write('\n');
write(color);
padding = self.tick ? '_' : '__';
var tail = self.tick ? '~' : '^';
var face;
write(tail + '|' + padding + this.face() + ' ');
write('\n');
write(color);
padding = self.tick ? ' ' : ' ';
write(padding + '"" "" ');
write('\n');
this.cursorUp(this.numberOfLines);
};
/**
* Draw nyan cat face.
*
* @return {String}
* @api private
*/
NyanCat.prototype.face = function() {
var stats = this.stats;
if (stats.failures) {
return '( x .x)';
} else if (stats.pending) {
return '( o .o)';
} else if(stats.passes) {
return '( ^ .^)';
} else {
return '( - .-)';
}
}
/**
* Move cursor up `n`.
*
* @param {Number} n
* @api private
*/
NyanCat.prototype.cursorUp = function(n) {
write('\u001b[' + n + 'A');
};
/**
* Move cursor down `n`.
*
* @param {Number} n
* @api private
*/
NyanCat.prototype.cursorDown = function(n) {
write('\u001b[' + n + 'B');
};
/**
* Generate rainbow colors.
*
* @return {Array}
* @api private
*/
NyanCat.prototype.generateColors = function(){
var colors = [];
for (var i = 0; i < (6 * 7); i++) {
var pi3 = Math.floor(Math.PI / 3);
var n = (i * (1.0 / 6));
var r = Math.floor(3 * Math.sin(n) + 3);
var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
colors.push(36 * r + 6 * g + b + 16);
}
return colors;
};
/**
* Apply rainbow to the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
NyanCat.prototype.rainbowify = function(str){
var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
this.colorIndex += 1;
return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
};
/**
* Stdout helper.
*/
function write(string) {
process.stdout.write(string);
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
NyanCat.prototype = new F;
NyanCat.prototype.constructor = NyanCat;
}); // module: reporters/nyan.js
require.register("reporters/progress.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `Progress`.
*/
exports = module.exports = Progress;
/**
* General progress bar color.
*/
Base.colors.progress = 90;
/**
* Initialize a new `Progress` bar test reporter.
*
* @param {Runner} runner
* @param {Object} options
* @api public
*/
function Progress(runner, options) {
Base.call(this, runner);
var self = this
, options = options || {}
, stats = this.stats
, width = Base.window.width * .50 | 0
, total = runner.total
, complete = 0
, max = Math.max;
// default chars
options.open = options.open || '[';
options.complete = options.complete || '▬';
options.incomplete = options.incomplete || Base.symbols.dot;
options.close = options.close || ']';
options.verbose = false;
// tests started
runner.on('start', function(){
console.log();
cursor.hide();
});
// tests complete
runner.on('test end', function(){
complete++;
var incomplete = total - complete
, percent = complete / total
, n = width * percent | 0
, i = width - n;
cursor.CR();
process.stdout.write('\u001b[J');
process.stdout.write(color('progress', ' ' + options.open));
process.stdout.write(Array(n).join(options.complete));
process.stdout.write(Array(i).join(options.incomplete));
process.stdout.write(color('progress', options.close));
if (options.verbose) {
process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
}
});
// tests are complete, output some stats
// and the failures if any
runner.on('end', function(){
cursor.show();
console.log();
self.epilogue();
});
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
Progress.prototype = new F;
Progress.prototype.constructor = Progress;
}); // module: reporters/progress.js
require.register("reporters/spec.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `Spec`.
*/
exports = module.exports = Spec;
/**
* Initialize a new `Spec` test reporter.
*
* @param {Runner} runner
* @api public
*/
function Spec(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, indents = 0
, n = 0;
function indent() {
return Array(indents).join(' ')
}
runner.on('start', function(){
console.log();
});
runner.on('suite', function(suite){
++indents;
console.log(color('suite', '%s%s'), indent(), suite.title);
});
runner.on('suite end', function(suite){
--indents;
if (1 == indents) console.log();
});
runner.on('pending', function(test){
var fmt = indent() + color('pending', ' - %s');
console.log(fmt, test.title);
});
runner.on('pass', function(test){
if ('fast' == test.speed) {
var fmt = indent()
+ color('checkmark', ' ' + Base.symbols.ok)
+ color('pass', ' %s ');
cursor.CR();
console.log(fmt, test.title);
} else {
var fmt = indent()
+ color('checkmark', ' ' + Base.symbols.ok)
+ color('pass', ' %s ')
+ color(test.speed, '(%dms)');
cursor.CR();
console.log(fmt, test.title, test.duration);
}
});
runner.on('fail', function(test, err){
cursor.CR();
console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
});
runner.on('end', self.epilogue.bind(self));
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
Spec.prototype = new F;
Spec.prototype.constructor = Spec;
}); // module: reporters/spec.js
require.register("reporters/tap.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, cursor = Base.cursor
, color = Base.color;
/**
* Expose `TAP`.
*/
exports = module.exports = TAP;
/**
* Initialize a new `TAP` reporter.
*
* @param {Runner} runner
* @api public
*/
function TAP(runner) {
Base.call(this, runner);
var self = this
, stats = this.stats
, n = 1
, passes = 0
, failures = 0;
runner.on('start', function(){
var total = runner.grepTotal(runner.suite);
console.log('%d..%d', 1, total);
});
runner.on('test end', function(){
++n;
});
runner.on('pending', function(test){
console.log('ok %d %s # SKIP -', n, title(test));
});
runner.on('pass', function(test){
passes++;
console.log('ok %d %s', n, title(test));
});
runner.on('fail', function(test, err){
failures++;
console.log('not ok %d %s', n, title(test));
if (err.stack) console.log(err.stack.replace(/^/gm, ' '));
});
runner.on('end', function(){
console.log('# tests ' + (passes + failures));
console.log('# pass ' + passes);
console.log('# fail ' + failures);
});
}
/**
* Return a TAP-safe title of `test`
*
* @param {Object} test
* @return {String}
* @api private
*/
function title(test) {
return test.fullTitle().replace(/#/g, '');
}
}); // module: reporters/tap.js
require.register("reporters/xunit.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Base = require('./base')
, utils = require('../utils')
, escape = utils.escape;
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
var Date = global.Date
, setTimeout = global.setTimeout
, setInterval = global.setInterval
, clearTimeout = global.clearTimeout
, clearInterval = global.clearInterval;
/**
* Expose `XUnit`.
*/
exports = module.exports = XUnit;
/**
* Initialize a new `XUnit` reporter.
*
* @param {Runner} runner
* @api public
*/
function XUnit(runner) {
Base.call(this, runner);
var stats = this.stats
, tests = []
, self = this;
runner.on('pending', function(test){
tests.push(test);
});
runner.on('pass', function(test){
tests.push(test);
});
runner.on('fail', function(test){
tests.push(test);
});
runner.on('end', function(){
console.log(tag('testsuite', {
name: 'Mocha Tests'
, tests: stats.tests
, failures: stats.failures
, errors: stats.failures
, skipped: stats.tests - stats.failures - stats.passes
, timestamp: (new Date).toUTCString()
, time: (stats.duration / 1000) || 0
}, false));
tests.forEach(test);
console.log('</testsuite>');
});
}
/**
* Inherit from `Base.prototype`.
*/
function F(){};
F.prototype = Base.prototype;
XUnit.prototype = new F;
XUnit.prototype.constructor = XUnit;
/**
* Output tag for the given `test.`
*/
function test(test) {
var attrs = {
classname: test.parent.fullTitle()
, name: test.title
, time: (test.duration / 1000) || 0
};
if ('failed' == test.state) {
var err = test.err;
attrs.message = escape(err.message);
console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
} else if (test.pending) {
console.log(tag('testcase', attrs, false, tag('skipped', {}, true)));
} else {
console.log(tag('testcase', attrs, true) );
}
}
/**
* HTML tag helper.
*/
function tag(name, attrs, close, content) {
var end = close ? '/>' : '>'
, pairs = []
, tag;
for (var key in attrs) {
pairs.push(key + '="' + escape(attrs[key]) + '"');
}
tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
if (content) tag += content + '</' + name + end;
return tag;
}
/**
* Return cdata escaped CDATA `str`.
*/
function cdata(str) {
return '<![CDATA[' + escape(str) + ']]>';
}
}); // module: reporters/xunit.js
require.register("runnable.js", function(module, exports, require){
/**
* Module dependencies.
*/
var EventEmitter = require('browser/events').EventEmitter
, debug = require('browser/debug')('mocha:runnable')
, milliseconds = require('./ms');
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
var Date = global.Date
, setTimeout = global.setTimeout
, setInterval = global.setInterval
, clearTimeout = global.clearTimeout
, clearInterval = global.clearInterval;
/**
* Object#toString().
*/
var toString = Object.prototype.toString;
/**
* Expose `Runnable`.
*/
module.exports = Runnable;
/**
* Initialize a new `Runnable` with the given `title` and callback `fn`.
*
* @param {String} title
* @param {Function} fn
* @api private
*/
function Runnable(title, fn) {
this.title = title;
this.fn = fn;
this.async = fn && fn.length;
this.sync = ! this.async;
this._timeout = 2000;
this._slow = 75;
this.timedOut = false;
}
/**
* Inherit from `EventEmitter.prototype`.
*/
function F(){};
F.prototype = EventEmitter.prototype;
Runnable.prototype = new F;
Runnable.prototype.constructor = Runnable;
/**
* Set & get timeout `ms`.
*
* @param {Number|String} ms
* @return {Runnable|Number} ms or self
* @api private
*/
Runnable.prototype.timeout = function(ms){
if (0 == arguments.length) return this._timeout;
if ('string' == typeof ms) ms = milliseconds(ms);
debug('timeout %d', ms);
this._timeout = ms;
if (this.timer) this.resetTimeout();
return this;
};
/**
* Set & get slow `ms`.
*
* @param {Number|String} ms
* @return {Runnable|Number} ms or self
* @api private
*/
Runnable.prototype.slow = function(ms){
if (0 === arguments.length) return this._slow;
if ('string' == typeof ms) ms = milliseconds(ms);
debug('timeout %d', ms);
this._slow = ms;
return this;
};
/**
* Return the full title generated by recursively
* concatenating the parent's full title.
*
* @return {String}
* @api public
*/
Runnable.prototype.fullTitle = function(){
return this.parent.fullTitle() + ' ' + this.title;
};
/**
* Clear the timeout.
*
* @api private
*/
Runnable.prototype.clearTimeout = function(){
clearTimeout(this.timer);
};
/**
* Inspect the runnable void of private properties.
*
* @return {String}
* @api private
*/
Runnable.prototype.inspect = function(){
return JSON.stringify(this, function(key, val){
if ('_' == key[0]) return;
if ('parent' == key) return '#<Suite>';
if ('ctx' == key) return '#<Context>';
return val;
}, 2);
};
/**
* Reset the timeout.
*
* @api private
*/
Runnable.prototype.resetTimeout = function(){
var self = this;
var ms = this.timeout() || 1e9;
this.clearTimeout();
this.timer = setTimeout(function(){
self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
self.timedOut = true;
}, ms);
};
/**
* Whitelist these globals for this test run
*
* @api private
*/
Runnable.prototype.globals = function(arr){
var self = this;
this._allowedGlobals = arr;
};
/**
* Run the test and invoke `fn(err)`.
*
* @param {Function} fn
* @api private
*/
Runnable.prototype.run = function(fn){
var self = this
, ms = this.timeout()
, start = new Date
, ctx = this.ctx
, finished
, emitted;
if (ctx) ctx.runnable(this);
// called multiple times
function multiple(err) {
if (emitted) return;
emitted = true;
self.emit('error', err || new Error('done() called multiple times'));
}
// finished
function done(err) {
if (self.timedOut) return;
if (finished) return multiple(err);
self.clearTimeout();
self.duration = new Date - start;
finished = true;
fn(err);
}
// for .resetTimeout()
this.callback = done;
// explicit async with `done` argument
if (this.async) {
this.resetTimeout();
try {
this.fn.call(ctx, function(err){
if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
done();
});
} catch (err) {
done(err);
}
return;
}
if (this.asyncOnly) {
return done(new Error('--async-only option in use without declaring `done()`'));
}
// sync or promise-returning
try {
if (this.pending) {
done();
} else {
callFn(this.fn);
}
} catch (err) {
done(err);
}
function callFn(fn) {
var result = fn.call(ctx);
if (result && typeof result.then === 'function') {
self.resetTimeout();
result.then(function(){ done() }, done);
} else {
done();
}
}
};
}); // module: runnable.js
require.register("runner.js", function(module, exports, require){
/**
* Module dependencies.
*/
var EventEmitter = require('browser/events').EventEmitter
, debug = require('browser/debug')('mocha:runner')
, Test = require('./test')
, utils = require('./utils')
, filter = utils.filter
, keys = utils.keys;
/**
* Non-enumerable globals.
*/
var globals = [
'setTimeout',
'clearTimeout',
'setInterval',
'clearInterval',
'XMLHttpRequest',
'Date'
];
/**
* Expose `Runner`.
*/
module.exports = Runner;
/**
* Initialize a `Runner` for the given `suite`.
*
* Events:
*
* - `start` execution started
* - `end` execution complete
* - `suite` (suite) test suite execution started
* - `suite end` (suite) all tests (and sub-suites) have finished
* - `test` (test) test execution started
* - `test end` (test) test completed
* - `hook` (hook) hook execution started
* - `hook end` (hook) hook complete
* - `pass` (test) test passed
* - `fail` (test, err) test failed
* - `pending` (test) test pending
*
* @api public
*/
function Runner(suite) {
var self = this;
this._globals = [];
this._abort = false;
this.suite = suite;
this.total = suite.total();
this.failures = 0;
this.on('test end', function(test){ self.checkGlobals(test); });
this.on('hook end', function(hook){ self.checkGlobals(hook); });
this.grep(/.*/);
this.globals(this.globalProps().concat(extraGlobals()));
}
/**
* Wrapper for setImmediate, process.nextTick, or browser polyfill.
*
* @param {Function} fn
* @api private
*/
Runner.immediately = global.setImmediate || process.nextTick;
/**
* Inherit from `EventEmitter.prototype`.
*/
function F(){};
F.prototype = EventEmitter.prototype;
Runner.prototype = new F;
Runner.prototype.constructor = Runner;
/**
* Run tests with full titles matching `re`. Updates runner.total
* with number of tests matched.
*
* @param {RegExp} re
* @param {Boolean} invert
* @return {Runner} for chaining
* @api public
*/
Runner.prototype.grep = function(re, invert){
debug('grep %s', re);
this._grep = re;
this._invert = invert;
this.total = this.grepTotal(this.suite);
return this;
};
/**
* Returns the number of tests matching the grep search for the
* given suite.
*
* @param {Suite} suite
* @return {Number}
* @api public
*/
Runner.prototype.grepTotal = function(suite) {
var self = this;
var total = 0;
suite.eachTest(function(test){
var match = self._grep.test(test.fullTitle());
if (self._invert) match = !match;
if (match) total++;
});
return total;
};
/**
* Return a list of global properties.
*
* @return {Array}
* @api private
*/
Runner.prototype.globalProps = function() {
var props = utils.keys(global);
// non-enumerables
for (var i = 0; i < globals.length; ++i) {
if (~utils.indexOf(props, globals[i])) continue;
props.push(globals[i]);
}
return props;
};
/**
* Allow the given `arr` of globals.
*
* @param {Array} arr
* @return {Runner} for chaining
* @api public
*/
Runner.prototype.globals = function(arr){
if (0 == arguments.length) return this._globals;
debug('globals %j', arr);
this._globals = this._globals.concat(arr);
return this;
};
/**
* Check for global variable leaks.
*
* @api private
*/
Runner.prototype.checkGlobals = function(test){
if (this.ignoreLeaks) return;
var ok = this._globals;
var globals = this.globalProps();
var isNode = process.kill;
var leaks;
if (test) {
ok = ok.concat(test._allowedGlobals || []);
}
if(this.prevGlobalsLength == globals.length) return;
this.prevGlobalsLength = globals.length;
leaks = filterLeaks(ok, globals);
this._globals = this._globals.concat(leaks);
if (leaks.length > 1) {
this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
} else if (leaks.length) {
this.fail(test, new Error('global leak detected: ' + leaks[0]));
}
};
/**
* Fail the given `test`.
*
* @param {Test} test
* @param {Error} err
* @api private
*/
Runner.prototype.fail = function(test, err){
++this.failures;
test.state = 'failed';
if ('string' == typeof err) {
err = new Error('the string "' + err + '" was thrown, throw an Error :)');
}
this.emit('fail', test, err);
};
/**
* Fail the given `hook` with `err`.
*
* Hook failures work in the following pattern:
* - If bail, then exit
* - Failed `before` hook skips all tests in a suite and subsuites,
* but jumps to corresponding `after` hook
* - Failed `before each` hook skips remaining tests in a
* suite and jumps to corresponding `after each` hook,
* which is run only once
* - Failed `after` hook does not alter
* execution order
* - Failed `after each` hook skips remaining tests in a
* suite and subsuites, but executes other `after each`
* hooks
*
* @param {Hook} hook
* @param {Error} err
* @api private
*/
Runner.prototype.failHook = function(hook, err){
this.fail(hook, err);
if (this.suite.bail()) {
this.emit('end');
}
};
/**
* Run hook `name` callbacks and then invoke `fn()`.
*
* @param {String} name
* @param {Function} function
* @api private
*/
Runner.prototype.hook = function(name, fn){
var suite = this.suite
, hooks = suite['_' + name]
, self = this
, timer;
function next(i) {
var hook = hooks[i];
if (!hook) return fn();
if (self.failures && suite.bail()) return fn();
self.currentRunnable = hook;
hook.ctx.currentTest = self.test;
self.emit('hook', hook);
hook.on('error', function(err){
self.failHook(hook, err);
});
hook.run(function(err){
hook.removeAllListeners('error');
var testError = hook.error();
if (testError) self.fail(self.test, testError);
if (err) {
self.failHook(hook, err);
// stop executing hooks, notify callee of hook err
return fn(err);
}
self.emit('hook end', hook);
delete hook.ctx.currentTest;
next(++i);
});
}
Runner.immediately(function(){
next(0);
});
};
/**
* Run hook `name` for the given array of `suites`
* in order, and callback `fn(err, errSuite)`.
*
* @param {String} name
* @param {Array} suites
* @param {Function} fn
* @api private
*/
Runner.prototype.hooks = function(name, suites, fn){
var self = this
, orig = this.suite;
function next(suite) {
self.suite = suite;
if (!suite) {
self.suite = orig;
return fn();
}
self.hook(name, function(err){
if (err) {
var errSuite = self.suite;
self.suite = orig;
return fn(err, errSuite);
}
next(suites.pop());
});
}
next(suites.pop());
};
/**
* Run hooks from the top level down.
*
* @param {String} name
* @param {Function} fn
* @api private
*/
Runner.prototype.hookUp = function(name, fn){
var suites = [this.suite].concat(this.parents()).reverse();
this.hooks(name, suites, fn);
};
/**
* Run hooks from the bottom up.
*
* @param {String} name
* @param {Function} fn
* @api private
*/
Runner.prototype.hookDown = function(name, fn){
var suites = [this.suite].concat(this.parents());
this.hooks(name, suites, fn);
};
/**
* Return an array of parent Suites from
* closest to furthest.
*
* @return {Array}
* @api private
*/
Runner.prototype.parents = function(){
var suite = this.suite
, suites = [];
while (suite = suite.parent) suites.push(suite);
return suites;
};
/**
* Run the current test and callback `fn(err)`.
*
* @param {Function} fn
* @api private
*/
Runner.prototype.runTest = function(fn){
var test = this.test
, self = this;
if (this.asyncOnly) test.asyncOnly = true;
try {
test.on('error', function(err){
self.fail(test, err);
});
test.run(fn);
} catch (err) {
fn(err);
}
};
/**
* Run tests in the given `suite` and invoke
* the callback `fn()` when complete.
*
* @param {Suite} suite
* @param {Function} fn
* @api private
*/
Runner.prototype.runTests = function(suite, fn){
var self = this
, tests = suite.tests.slice()
, test;
function hookErr(err, errSuite, after) {
// before/after Each hook for errSuite failed:
var orig = self.suite;
// for failed 'after each' hook start from errSuite parent,
// otherwise start from errSuite itself
self.suite = after ? errSuite.parent : errSuite;
if (self.suite) {
// call hookUp afterEach
self.hookUp('afterEach', function(err2, errSuite2) {
self.suite = orig;
// some hooks may fail even now
if (err2) return hookErr(err2, errSuite2, true);
// report error suite
fn(errSuite);
});
} else {
// there is no need calling other 'after each' hooks
self.suite = orig;
fn(errSuite);
}
}
function next(err, errSuite) {
// if we bail after first err
if (self.failures && suite._bail) return fn();
if (self._abort) return fn();
if (err) return hookErr(err, errSuite, true);
// next test
test = tests.shift();
// all done
if (!test) return fn();
// grep
var match = self._grep.test(test.fullTitle());
if (self._invert) match = !match;
if (!match) return next();
// pending
if (test.pending) {
self.emit('pending', test);
self.emit('test end', test);
return next();
}
// execute test and hook(s)
self.emit('test', self.test = test);
self.hookDown('beforeEach', function(err, errSuite){
if (err) return hookErr(err, errSuite, false);
self.currentRunnable = self.test;
self.runTest(function(err){
test = self.test;
if (err) {
self.fail(test, err);
self.emit('test end', test);
return self.hookUp('afterEach', next);
}
test.state = 'passed';
self.emit('pass', test);
self.emit('test end', test);
self.hookUp('afterEach', next);
});
});
}
this.next = next;
next();
};
/**
* Run the given `suite` and invoke the
* callback `fn()` when complete.
*
* @param {Suite} suite
* @param {Function} fn
* @api private
*/
Runner.prototype.runSuite = function(suite, fn){
var total = this.grepTotal(suite)
, self = this
, i = 0;
debug('run suite %s', suite.fullTitle());
if (!total) return fn();
this.emit('suite', this.suite = suite);
function next(errSuite) {
if (errSuite) {
// current suite failed on a hook from errSuite
if (errSuite == suite) {
// if errSuite is current suite
// continue to the next sibling suite
return done();
} else {
// errSuite is among the parents of current suite
// stop execution of errSuite and all sub-suites
return done(errSuite);
}
}
if (self._abort) return done();
var curr = suite.suites[i++];
if (!curr) return done();
self.runSuite(curr, next);
}
function done(errSuite) {
self.suite = suite;
self.hook('afterAll', function(){
self.emit('suite end', suite);
fn(errSuite);
});
}
this.hook('beforeAll', function(err){
if (err) return done();
self.runTests(suite, next);
});
};
/**
* Handle uncaught exceptions.
*
* @param {Error} err
* @api private
*/
Runner.prototype.uncaught = function(err){
debug('uncaught exception %s', err.message);
var runnable = this.currentRunnable;
if (!runnable || 'failed' == runnable.state) return;
runnable.clearTimeout();
err.uncaught = true;
this.fail(runnable, err);
// recover from test
if ('test' == runnable.type) {
this.emit('test end', runnable);
this.hookUp('afterEach', this.next);
return;
}
// bail on hooks
this.emit('end');
};
/**
* Run the root suite and invoke `fn(failures)`
* on completion.
*
* @param {Function} fn
* @return {Runner} for chaining
* @api public
*/
Runner.prototype.run = function(fn){
var self = this
, fn = fn || function(){};
function uncaught(err){
self.uncaught(err);
}
debug('start');
// callback
this.on('end', function(){
debug('end');
process.removeListener('uncaughtException', uncaught);
fn(self.failures);
});
// run suites
this.emit('start');
this.runSuite(this.suite, function(){
debug('finished running');
self.emit('end');
});
// uncaught exception
process.on('uncaughtException', uncaught);
return this;
};
/**
* Cleanly abort execution
*
* @return {Runner} for chaining
* @api public
*/
Runner.prototype.abort = function(){
debug('aborting');
this._abort = true;
}
/**
* Filter leaks with the given globals flagged as `ok`.
*
* @param {Array} ok
* @param {Array} globals
* @return {Array}
* @api private
*/
function filterLeaks(ok, globals) {
return filter(globals, function(key){
// Firefox and Chrome exposes iframes as index inside the window object
if (/^d+/.test(key)) return false;
// in firefox
// if runner runs in an iframe, this iframe's window.getInterface method not init at first
// it is assigned in some seconds
if (global.navigator && /^getInterface/.test(key)) return false;
// an iframe could be approached by window[iframeIndex]
// in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
if (global.navigator && /^\d+/.test(key)) return false;
// Opera and IE expose global variables for HTML element IDs (issue #243)
if (/^mocha-/.test(key)) return false;
var matched = filter(ok, function(ok){
if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
return key == ok;
});
return matched.length == 0 && (!global.navigator || 'onerror' !== key);
});
}
/**
* Array of globals dependent on the environment.
*
* @return {Array}
* @api private
*/
function extraGlobals() {
if (typeof(process) === 'object' &&
typeof(process.version) === 'string') {
var nodeVersion = process.version.split('.').reduce(function(a, v) {
return a << 8 | v;
});
// 'errno' was renamed to process._errno in v0.9.11.
if (nodeVersion < 0x00090B) {
return ['errno'];
}
}
return [];
}
}); // module: runner.js
require.register("suite.js", function(module, exports, require){
/**
* Module dependencies.
*/
var EventEmitter = require('browser/events').EventEmitter
, debug = require('browser/debug')('mocha:suite')
, milliseconds = require('./ms')
, utils = require('./utils')
, Hook = require('./hook');
/**
* Expose `Suite`.
*/
exports = module.exports = Suite;
/**
* Create a new `Suite` with the given `title`
* and parent `Suite`. When a suite with the
* same title is already present, that suite
* is returned to provide nicer reporter
* and more flexible meta-testing.
*
* @param {Suite} parent
* @param {String} title
* @return {Suite}
* @api public
*/
exports.create = function(parent, title){
var suite = new Suite(title, parent.ctx);
suite.parent = parent;
if (parent.pending) suite.pending = true;
title = suite.fullTitle();
parent.addSuite(suite);
return suite;
};
/**
* Initialize a new `Suite` with the given
* `title` and `ctx`.
*
* @param {String} title
* @param {Context} ctx
* @api private
*/
function Suite(title, parentContext) {
this.title = title;
var context = function () {};
context.prototype = parentContext;
this.ctx = new context();
this.suites = [];
this.tests = [];
this.pending = false;
this._beforeEach = [];
this._beforeAll = [];
this._afterEach = [];
this._afterAll = [];
this.root = !title;
this._timeout = 2000;
this._slow = 75;
this._bail = false;
}
/**
* Inherit from `EventEmitter.prototype`.
*/
function F(){};
F.prototype = EventEmitter.prototype;
Suite.prototype = new F;
Suite.prototype.constructor = Suite;
/**
* Return a clone of this `Suite`.
*
* @return {Suite}
* @api private
*/
Suite.prototype.clone = function(){
var suite = new Suite(this.title);
debug('clone');
suite.ctx = this.ctx;
suite.timeout(this.timeout());
suite.slow(this.slow());
suite.bail(this.bail());
return suite;
};
/**
* Set timeout `ms` or short-hand such as "2s".
*
* @param {Number|String} ms
* @return {Suite|Number} for chaining
* @api private
*/
Suite.prototype.timeout = function(ms){
if (0 == arguments.length) return this._timeout;
if ('string' == typeof ms) ms = milliseconds(ms);
debug('timeout %d', ms);
this._timeout = parseInt(ms, 10);
return this;
};
/**
* Set slow `ms` or short-hand such as "2s".
*
* @param {Number|String} ms
* @return {Suite|Number} for chaining
* @api private
*/
Suite.prototype.slow = function(ms){
if (0 === arguments.length) return this._slow;
if ('string' == typeof ms) ms = milliseconds(ms);
debug('slow %d', ms);
this._slow = ms;
return this;
};
/**
* Sets whether to bail after first error.
*
* @parma {Boolean} bail
* @return {Suite|Number} for chaining
* @api private
*/
Suite.prototype.bail = function(bail){
if (0 == arguments.length) return this._bail;
debug('bail %s', bail);
this._bail = bail;
return this;
};
/**
* Run `fn(test[, done])` before running tests.
*
* @param {Function} fn
* @return {Suite} for chaining
* @api private
*/
Suite.prototype.beforeAll = function(title, fn){
if (this.pending) return this;
if ('function' === typeof title) {
fn = title;
title = fn.name;
}
title = '"before all" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._beforeAll.push(hook);
this.emit('beforeAll', hook);
return this;
};
/**
* Run `fn(test[, done])` after running tests.
*
* @param {Function} fn
* @return {Suite} for chaining
* @api private
*/
Suite.prototype.afterAll = function(title, fn){
if (this.pending) return this;
if ('function' === typeof title) {
fn = title;
title = fn.name;
}
title = '"after all" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._afterAll.push(hook);
this.emit('afterAll', hook);
return this;
};
/**
* Run `fn(test[, done])` before each test case.
*
* @param {Function} fn
* @return {Suite} for chaining
* @api private
*/
Suite.prototype.beforeEach = function(title, fn){
if (this.pending) return this;
if ('function' === typeof title) {
fn = title;
title = fn.name;
}
title = '"before each" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._beforeEach.push(hook);
this.emit('beforeEach', hook);
return this;
};
/**
* Run `fn(test[, done])` after each test case.
*
* @param {Function} fn
* @return {Suite} for chaining
* @api private
*/
Suite.prototype.afterEach = function(title, fn){
if (this.pending) return this;
if ('function' === typeof title) {
fn = title;
title = fn.name;
}
title = '"after each" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._afterEach.push(hook);
this.emit('afterEach', hook);
return this;
};
/**
* Add a test `suite`.
*
* @param {Suite} suite
* @return {Suite} for chaining
* @api private
*/
Suite.prototype.addSuite = function(suite){
suite.parent = this;
suite.timeout(this.timeout());
suite.slow(this.slow());
suite.bail(this.bail());
this.suites.push(suite);
this.emit('suite', suite);
return this;
};
/**
* Add a `test` to this suite.
*
* @param {Test} test
* @return {Suite} for chaining
* @api private
*/
Suite.prototype.addTest = function(test){
test.parent = this;
test.timeout(this.timeout());
test.slow(this.slow());
test.ctx = this.ctx;
this.tests.push(test);
this.emit('test', test);
return this;
};
/**
* Return the full title generated by recursively
* concatenating the parent's full title.
*
* @return {String}
* @api public
*/
Suite.prototype.fullTitle = function(){
if (this.parent) {
var full = this.parent.fullTitle();
if (full) return full + ' ' + this.title;
}
return this.title;
};
/**
* Return the total number of tests.
*
* @return {Number}
* @api public
*/
Suite.prototype.total = function(){
return utils.reduce(this.suites, function(sum, suite){
return sum + suite.total();
}, 0) + this.tests.length;
};
/**
* Iterates through each suite recursively to find
* all tests. Applies a function in the format
* `fn(test)`.
*
* @param {Function} fn
* @return {Suite}
* @api private
*/
Suite.prototype.eachTest = function(fn){
utils.forEach(this.tests, fn);
utils.forEach(this.suites, function(suite){
suite.eachTest(fn);
});
return this;
};
}); // module: suite.js
require.register("test.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Runnable = require('./runnable');
/**
* Expose `Test`.
*/
module.exports = Test;
/**
* Initialize a new `Test` with the given `title` and callback `fn`.
*
* @param {String} title
* @param {Function} fn
* @api private
*/
function Test(title, fn) {
Runnable.call(this, title, fn);
this.pending = !fn;
this.type = 'test';
}
/**
* Inherit from `Runnable.prototype`.
*/
function F(){};
F.prototype = Runnable.prototype;
Test.prototype = new F;
Test.prototype.constructor = Test;
}); // module: test.js
require.register("utils.js", function(module, exports, require){
/**
* Module dependencies.
*/
var fs = require('browser/fs')
, path = require('browser/path')
, join = path.join
, debug = require('browser/debug')('mocha:watch');
/**
* Ignored directories.
*/
var ignore = ['node_modules', '.git'];
/**
* Escape special characters in the given string of html.
*
* @param {String} html
* @return {String}
* @api private
*/
exports.escape = function(html){
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
};
/**
* Array#forEach (<=IE8)
*
* @param {Array} array
* @param {Function} fn
* @param {Object} scope
* @api private
*/
exports.forEach = function(arr, fn, scope){
for (var i = 0, l = arr.length; i < l; i++)
fn.call(scope, arr[i], i);
};
/**
* Array#map (<=IE8)
*
* @param {Array} array
* @param {Function} fn
* @param {Object} scope
* @api private
*/
exports.map = function(arr, fn, scope){
var result = [];
for (var i = 0, l = arr.length; i < l; i++)
result.push(fn.call(scope, arr[i], i));
return result;
};
/**
* Array#indexOf (<=IE8)
*
* @parma {Array} arr
* @param {Object} obj to find index of
* @param {Number} start
* @api private
*/
exports.indexOf = function(arr, obj, start){
for (var i = start || 0, l = arr.length; i < l; i++) {
if (arr[i] === obj)
return i;
}
return -1;
};
/**
* Array#reduce (<=IE8)
*
* @param {Array} array
* @param {Function} fn
* @param {Object} initial value
* @api private
*/
exports.reduce = function(arr, fn, val){
var rval = val;
for (var i = 0, l = arr.length; i < l; i++) {
rval = fn(rval, arr[i], i, arr);
}
return rval;
};
/**
* Array#filter (<=IE8)
*
* @param {Array} array
* @param {Function} fn
* @api private
*/
exports.filter = function(arr, fn){
var ret = [];
for (var i = 0, l = arr.length; i < l; i++) {
var val = arr[i];
if (fn(val, i, arr)) ret.push(val);
}
return ret;
};
/**
* Object.keys (<=IE8)
*
* @param {Object} obj
* @return {Array} keys
* @api private
*/
exports.keys = Object.keys || function(obj) {
var keys = []
, has = Object.prototype.hasOwnProperty // for `window` on <=IE8
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Watch the given `files` for changes
* and invoke `fn(file)` on modification.
*
* @param {Array} files
* @param {Function} fn
* @api private
*/
exports.watch = function(files, fn){
var options = { interval: 100 };
files.forEach(function(file){
debug('file %s', file);
fs.watchFile(file, options, function(curr, prev){
if (prev.mtime < curr.mtime) fn(file);
});
});
};
/**
* Ignored files.
*/
function ignored(path){
return !~ignore.indexOf(path);
}
/**
* Lookup files in the given `dir`.
*
* @return {Array}
* @api private
*/
exports.files = function(dir, ret){
ret = ret || [];
fs.readdirSync(dir)
.filter(ignored)
.forEach(function(path){
path = join(dir, path);
if (fs.statSync(path).isDirectory()) {
exports.files(path, ret);
} else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) {
ret.push(path);
}
});
return ret;
};
/**
* Compute a slug from the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
exports.slug = function(str){
return str
.toLowerCase()
.replace(/ +/g, '-')
.replace(/[^-\w]/g, '');
};
/**
* Strip the function definition from `str`,
* and re-indent for pre whitespace.
*/
exports.clean = function(str) {
str = str
.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
.replace(/^function *\(.*\) *{/, '')
.replace(/\s+\}$/, '');
var spaces = str.match(/^\n?( *)/)[1].length
, tabs = str.match(/^\n?(\t*)/)[1].length
, re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');
str = str.replace(re, '');
return exports.trim(str);
};
/**
* Escape regular expression characters in `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
exports.escapeRegexp = function(str){
return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};
/**
* Trim the given `str`.
*
* @param {String} str
* @return {String}
* @api private
*/
exports.trim = function(str){
return str.replace(/^\s+|\s+$/g, '');
};
/**
* Parse the given `qs`.
*
* @param {String} qs
* @return {Object}
* @api private
*/
exports.parseQuery = function(qs){
return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
var i = pair.indexOf('=')
, key = pair.slice(0, i)
, val = pair.slice(++i);
obj[key] = decodeURIComponent(val);
return obj;
}, {});
};
/**
* Highlight the given string of `js`.
*
* @param {String} js
* @return {String}
* @api private
*/
function highlight(js) {
return js
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
.replace(/('.*?')/gm, '<span class="string">$1</span>')
.replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
.replace(/(\d+)/gm, '<span class="number">$1</span>')
.replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
.replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
}
/**
* Highlight the contents of tag `name`.
*
* @param {String} name
* @api private
*/
exports.highlightTags = function(name) {
var code = document.getElementsByTagName(name);
for (var i = 0, len = code.length; i < len; ++i) {
code[i].innerHTML = highlight(code[i].innerHTML);
}
};
}); // module: utils.js
// The global object is "self" in Web Workers.
global = (function() { return this; })();
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
var Date = global.Date;
var setTimeout = global.setTimeout;
var setInterval = global.setInterval;
var clearTimeout = global.clearTimeout;
var clearInterval = global.clearInterval;
/**
* Node shims.
*
* These are meant only to allow
* mocha.js to run untouched, not
* to allow running node code in
* the browser.
*/
var process = {};
process.exit = function(status){};
process.stdout = {};
var uncaughtExceptionHandlers = [];
/**
* Remove uncaughtException listener.
*/
process.removeListener = function(e, fn){
if ('uncaughtException' == e) {
global.onerror = function() {};
var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn);
if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); }
}
};
/**
* Implements uncaughtException listener.
*/
process.on = function(e, fn){
if ('uncaughtException' == e) {
global.onerror = function(err, url, line){
fn(new Error(err + ' (' + url + ':' + line + ')'));
return true;
};
uncaughtExceptionHandlers.push(fn);
}
};
/**
* Expose mocha.
*/
var Mocha = global.Mocha = require('mocha'),
mocha = global.mocha = new Mocha({ reporter: 'html' });
// The BDD UI is registered by default, but no UI will be functional in the
// browser without an explicit call to the overridden `mocha.ui` (see below).
// Ensure that this default UI does not expose its methods to the global scope.
mocha.suite.removeAllListeners('pre-require');
var immediateQueue = []
, immediateTimeout;
function timeslice() {
var immediateStart = new Date().getTime();
while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
immediateQueue.shift()();
}
if (immediateQueue.length) {
immediateTimeout = setTimeout(timeslice, 0);
} else {
immediateTimeout = null;
}
}
/**
* High-performance override of Runner.immediately.
*/
Mocha.Runner.immediately = function(callback) {
immediateQueue.push(callback);
if (!immediateTimeout) {
immediateTimeout = setTimeout(timeslice, 0);
}
};
/**
* Function to allow assertion libraries to throw errors directly into mocha.
* This is useful when running tests in a browser because window.onerror will
* only receive the 'message' attribute of the Error.
*/
mocha.throwError = function(err) {
Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) {
fn(err);
});
throw err;
};
/**
* Override ui to ensure that the ui functions are initialized.
* Normally this would happen in Mocha.prototype.loadFiles.
*/
mocha.ui = function(ui){
Mocha.prototype.ui.call(this, ui);
this.suite.emit('pre-require', global, null, this);
return this;
};
/**
* Setup mocha with the given setting options.
*/
mocha.setup = function(opts){
if ('string' == typeof opts) opts = { ui: opts };
for (var opt in opts) this[opt](opts[opt]);
return this;
};
/**
* Run mocha, returning the Runner.
*/
mocha.run = function(fn){
var options = mocha.options;
mocha.globals('location');
var query = Mocha.utils.parseQuery(global.location.search || '');
if (query.grep) mocha.grep(query.grep);
if (query.invert) mocha.invert();
return Mocha.prototype.run.call(mocha, function(){
// The DOM Document is not available in Web Workers.
if (global.document) {
Mocha.utils.highlightTags('code');
}
if (fn) fn();
});
};
/**
* Expose the process shim.
*/
Mocha.process = process;
})(); | agraebe/cdnjs | ajax/libs/mocha/1.20.0/mocha.js | JavaScript | mit | 124,054 |
YUI.add('io-upload-iframe', function(Y) {
/**
Extends the IO to enable file uploads, with HTML forms
using an iframe as the transport medium.
@module io
@submodule io-upload-iframe
@for IO
**/
var w = Y.config.win,
d = Y.config.doc,
_std = (d.documentMode && d.documentMode >= 8),
_d = decodeURIComponent;
/**
* Creates the iframe transported used in file upload
* transactions, and binds the response event handler.
*
* @method _cFrame
* @private
* @param {Object} o Transaction object generated by _create().
* @param {Object} c Configuration object passed to YUI.io().
* @param {Object} io
*/
function _cFrame(o, c, io) {
var i = Y.Node.create('<iframe src="#" id="io_iframe' + o.id + '" name="io_iframe' + o.id + '" />');
i._node.style.position = 'absolute';
i._node.style.top = '-1000px';
i._node.style.left = '-1000px';
Y.one('body').appendChild(i);
// Bind the onload handler to the iframe to detect the file upload response.
Y.on("load", function() { io._uploadComplete(o, c); }, '#io_iframe' + o.id);
}
/**
* Removes the iframe transport used in the file upload
* transaction.
*
* @method _dFrame
* @private
* @param {Number} id The transaction ID used in the iframe's creation.
*/
function _dFrame(id) {
Y.Event.purgeElement('#io_iframe' + id, false);
Y.one('body').removeChild(Y.one('#io_iframe' + id));
}
Y.mix(Y.IO.prototype, {
/**
* Parses the POST data object and creates hidden form elements
* for each key-value, and appends them to the HTML form object.
* @method appendData
* @private
* @static
* @param {Object} f HTML form object.
* @param {String} s The key-value POST data.
* @return {Array} o Array of created fields.
*/
_addData: function(f, s) {
// Serialize an object into a key-value string using
// querystring-stringify-simple.
if (Y.Lang.isObject(s)) {
s = Y.QueryString.stringify(s);
}
var o = [],
m = s.split('='),
i, l;
for (i = 0, l = m.length - 1; i < l; i++) {
o[i] = d.createElement('input');
o[i].type = 'hidden';
o[i].name = _d(m[i].substring(m[i].lastIndexOf('&') + 1));
o[i].value = (i + 1 === l) ? _d(m[i + 1]) : _d(m[i + 1].substring(0, (m[i + 1].lastIndexOf('&'))));
f.appendChild(o[i]);
}
return o;
},
/**
* Removes the custom fields created to pass additional POST
* data, along with the HTML form fields.
* @method _removeData
* @private
* @static
* @param {Object} f HTML form object.
* @param {Object} o HTML form fields created from configuration.data.
*/
_removeData: function(f, o) {
var i, l;
for (i = 0, l = o.length; i < l; i++) {
f.removeChild(o[i]);
}
},
/**
* Sets the appropriate attributes and values to the HTML
* form, in preparation of a file upload transaction.
* @method _setAttrs
* @private
* @static
* @param {Object} f HTML form object.
* @param {Object} id The Transaction ID.
* @param {Object} uri Qualified path to transaction resource.
*/
_setAttrs: function(f, id, uri) {
f.setAttribute('action', uri);
f.setAttribute('method', 'POST');
f.setAttribute('target', 'io_iframe' + id );
f.setAttribute(Y.UA.ie && !_std ? 'encoding' : 'enctype', 'multipart/form-data');
},
/**
* Reset the HTML form attributes to their original values.
* @method _resetAttrs
* @private
* @static
* @param {Object} f HTML form object.
* @param {Object} a Object of original attributes.
*/
_resetAttrs: function(f, a) {
Y.Object.each(a, function(v, p) {
if (v) {
f.setAttribute(p, v);
}
else {
f.removeAttribute(p);
}
});
},
/**
* Starts timeout count if the configuration object
* has a defined timeout property.
*
* @method _startUploadTimeout
* @private
* @static
* @param {Object} o Transaction object generated by _create().
* @param {Object} c Configuration object passed to YUI.io().
*/
_startUploadTimeout: function(o, c) {
var io = this;
io._timeout[o.id] = w.setTimeout(
function() {
o.status = 0;
o.statusText = 'timeout';
io.complete(o, c);
io.end(o, c);
}, c.timeout);
},
/**
* Clears the timeout interval started by _startUploadTimeout().
* @method _clearUploadTimeout
* @private
* @static
* @param {Number} id - Transaction ID.
*/
_clearUploadTimeout: function(id) {
var io = this;
w.clearTimeout(io._timeout[id]);
delete io._timeout[id];
},
/**
* Bound to the iframe's Load event and processes
* the response data.
* @method _uploadComplete
* @private
* @static
* @param {Object} o The transaction object
* @param {Object} c Configuration object for the transaction.
*/
_uploadComplete: function(o, c) {
var io = this,
d = Y.one('#io_iframe' + o.id).get('contentWindow.document'),
b = d.one('body'),
p;
if (c.timeout) {
io._clearUploadTimeout(o.id);
}
try {
if (b) {
// When a response Content-Type of "text/plain" is used, Firefox and Safari
// will wrap the response string with <pre></pre>.
p = b.one('pre:first-child');
o.c.responseText = p ? p.get('text') : b.get('text');
}
else {
o.c.responseXML = d._node;
}
}
catch (e) {
o.e = "upload failure";
}
io.complete(o, c);
io.end(o, c);
// The transaction is complete, so call _dFrame to remove
// the event listener bound to the iframe transport, and then
// destroy the iframe.
w.setTimeout( function() { _dFrame(o.id); }, 0);
},
/**
* Uploads HTML form data, inclusive of files/attachments,
* using the iframe created in _create to facilitate the transaction.
* @method _upload
* @private
* @static
* @param {Object} o The transaction object
* @param {Object} uri Qualified path to transaction resource.
* @param {Object} c Configuration object for the transaction.
*/
_upload: function(o, uri, c) {
var io = this,
f = (typeof c.form.id === 'string') ? d.getElementById(c.form.id) : c.form.id,
// Track original HTML form attribute values.
attr = {
action: f.getAttribute('action'),
target: f.getAttribute('target')
},
fields;
// Initialize the HTML form properties in case they are
// not defined in the HTML form.
io._setAttrs(f, o.id, uri);
if (c.data) {
fields = io._addData(f, c.data);
}
// Start polling if a callback is present and the timeout
// property has been defined.
if (c.timeout) {
io._startUploadTimeout(o, c);
}
// Start file upload.
f.submit();
io.start(o, c);
if (c.data) {
io._removeData(f, fields);
}
// Restore HTML form attributes to their original values.
io._resetAttrs(f, attr);
return {
id: o.id,
abort: function() {
o.status = 0;
o.statusText = 'abort';
if (Y.one('#io_iframe' + o.id)) {
_dFrame(o.id);
io.complete(o, c);
io.end(o, c);
}
else {
return false;
}
},
isInProgress: function() {
return Y.one('#io_iframe' + o.id) ? true : false;
},
io: io
};
},
upload: function(o, uri, c) {
_cFrame(o, c, this);
return this._upload(o, uri, c);
}
});
}, '@VERSION@' ,{requires:['io-base','node-base']});
| pvnr0082t/cdnjs | ajax/libs/yui/3.5.1/io-upload-iframe/io-upload-iframe.js | JavaScript | mit | 8,184 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 1.3.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Postgre Utility Class
*
* @package CodeIgniter
* @subpackage Drivers
* @category Database
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
class CI_DB_postgre_utility extends CI_DB_utility {
/**
* List databases statement
*
* @var string
*/
protected $_list_databases = 'SELECT datname FROM pg_database';
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $_optimize_table = 'REINDEX TABLE %s';
// --------------------------------------------------------------------
/**
* Export
*
* @param array $params Preferences
* @return mixed
*/
protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsupported_feature');
}
}
| mnalbantov/reward | sys/database/drivers/postgre/postgre_utility.php | PHP | mit | 2,505 |
<div ng-controller="ButtonsCtrl">
<h4>Single toggle</h4>
<pre>{{singleModel}}</pre>
<button type="button" class="btn btn-primary" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
Single Toggle
</button>
<h4>Checkbox</h4>
<pre>Model: {{checkModel}}</pre>
<pre>Results: {{checkResults}}</pre>
<div class="btn-group">
<label class="btn btn-primary" ng-model="checkModel.left" uib-btn-checkbox>Left</label>
<label class="btn btn-primary" ng-model="checkModel.middle" uib-btn-checkbox>Middle</label>
<label class="btn btn-primary" ng-model="checkModel.right" uib-btn-checkbox>Right</label>
</div>
<h4>Radio & Uncheckable Radio</h4>
<pre>{{radioModel || 'null'}}</pre>
<div class="btn-group">
<label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Left'">Left</label>
<label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Middle'">Middle</label>
<label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Right'">Right</label>
</div>
<div class="btn-group">
<label class="btn btn-success" ng-model="radioModel" uib-btn-radio="'Left'" uncheckable>Left</label>
<label class="btn btn-success" ng-model="radioModel" uib-btn-radio="'Middle'" uncheckable>Middle</label>
<label class="btn btn-success" ng-model="radioModel" uib-btn-radio="'Right'" uncheckable>Right</label>
</div>
</div>
| DTAFormation/pizzeria-web-admin-nov-2015 | lib/ui-bootstrap/src/buttons/docs/demo.html | HTML | mit | 1,495 |
/*
jasmine-given 2.1.0
Adds a Given-When-Then DSL to jasmine as an alternative style for specs
site: https://github.com/searls/jasmine-given
*/
(function() {
(function(jasmine) {
var getBlock, invariantList, mostRecentExpectations, mostRecentlyUsed, o, root, stringifyExpectation, whenList;
mostRecentlyUsed = null;
stringifyExpectation = function(expectation) {
var matches;
matches = expectation.toString().replace(/\n/g, '').match(/function\s?\(\)\s?{\s*(return\s+)?(.*?)(;)?\s*}/i);
if (matches && matches.length >= 3) {
return matches[2];
} else {
return "";
}
};
beforeEach(function() {
return this.addMatchers({
toHaveReturnedFalseFromThen: function(context, n) {
var exception, result;
result = false;
exception = void 0;
try {
result = this.actual.call(context);
} catch (e) {
exception = e;
}
this.message = function() {
var msg;
msg = "Then clause " + (n > 1 ? " #" + n : "") + " `" + (stringifyExpectation(this.actual)) + "` failed by ";
if (exception) {
msg += "throwing: " + exception.toString();
} else {
msg += "returning false";
}
return msg;
};
return result === false;
}
});
});
root = this;
root.Given = function() {
mostRecentlyUsed = root.Given;
return beforeEach(getBlock(arguments));
};
whenList = [];
root.When = function() {
var b;
mostRecentlyUsed = root.When;
b = getBlock(arguments);
beforeEach(function() {
return whenList.push(b);
});
return afterEach(function() {
return whenList.pop();
});
};
invariantList = [];
root.Invariant = function() {
var b;
mostRecentlyUsed = root.Invariant;
b = getBlock(arguments);
beforeEach(function() {
return invariantList.push(b);
});
return afterEach(function() {
return invariantList.pop();
});
};
getBlock = function(thing) {
var assignResultTo, setupFunction;
setupFunction = o(thing).firstThat(function(arg) {
return o(arg).isFunction();
});
assignResultTo = o(thing).firstThat(function(arg) {
return o(arg).isString();
});
return function() {
var context, result;
context = jasmine.getEnv().currentSpec;
result = setupFunction.call(context);
if (assignResultTo) {
if (!context[assignResultTo]) {
return context[assignResultTo] = result;
} else {
throw new Error("Unfortunately, the variable '" + assignResultTo + "' is already assigned to: " + context[assignResultTo]);
}
}
};
};
mostRecentExpectations = null;
root.Then = function() {
var expectationFunction, expectations, label;
label = o(arguments).firstThat(function(arg) {
return o(arg).isString();
});
expectationFunction = o(arguments).firstThat(function(arg) {
return o(arg).isFunction();
});
mostRecentlyUsed = root.subsequentThen;
mostRecentExpectations = expectations = [expectationFunction];
it("then " + (label != null ? label : stringifyExpectation(expectations)), function() {
var block, i, _i, _len, _ref, _results;
_ref = whenList != null ? whenList : [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
block = _ref[_i];
block();
}
i = 0;
expectations = invariantList.concat(expectations);
_results = [];
while (i < expectations.length) {
expect(expectations[i]).not.toHaveReturnedFalseFromThen(jasmine.getEnv().currentSpec, i + 1);
_results.push(i++);
}
return _results;
});
return {
Then: subsequentThen,
And: subsequentThen
};
};
root.subsequentThen = function(additionalExpectation) {
mostRecentExpectations.push(additionalExpectation);
return this;
};
mostRecentlyUsed = root.Given;
root.And = function() {
return mostRecentlyUsed.apply(this, jasmine.util.argsToArray(arguments));
};
return o = function(thing) {
return {
isFunction: function() {
return Object.prototype.toString.call(thing) === "[object Function]";
},
isString: function() {
return Object.prototype.toString.call(thing) === "[object String]";
},
firstThat: function(test) {
var i;
i = 0;
while (i < thing.length) {
if (test(thing[i]) === true) {
return thing[i];
}
i++;
}
return void 0;
}
};
};
})(jasmine);
}).call(this);
| searls/extend.js | spec/helpers/jasmine-given.js | JavaScript | mit | 4,942 |
/*! jQuery UI Virtual Keyboard v1.25.0 */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&"object"==typeof module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){"use strict";var b=a.keyboard=function(c,d){var e,f=this;f.version="1.25.0",f.$el=a(c),f.el=c,f.$el.data("keyboard",f),f.init=function(){var c,g=b.css;f.settings=d||{},d&&d.position&&(c=a.extend({},d.position),d.position=null),f.options=e=a.extend(!0,{},b.defaultOptions,d),c&&(e.position=c,d.position=c),f.el.active=!0,f.namespace=".keyboard"+Math.random().toString(16).slice(2),f.extensionNamespace=[],f.shiftActive=f.altActive=f.metaActive=f.sets=f.capsLock=!1,f.rows=["","-shift","-alt","-alt-shift"],f.inPlaceholder=f.$el.attr("placeholder")||"",f.watermark=b.watermark&&""!==f.inPlaceholder,f.repeatTime=1e3/(e.repeatRate||20),e.preventDoubleEventTime=e.preventDoubleEventTime||100,f.isOpen=!1,f.wheel=a.isFunction(a.fn.mousewheel),f.alwaysAllowed=[20,33,34,35,36,37,38,39,40,45,46],f.$keyboard=[],f.enabled=!0,a.isEmptyObject(e.position)||(e.position.orig_at=e.position.at),f.checkCaret=e.lockInput||b.checkCaretSupport(),f.last={start:0,end:0,key:"",val:"",layout:"",virtual:!0,keyset:[!1,!1,!1],wheel_$Keys:null,wheelIndex:0,wheelLayers:[]},f.temp=["",0,0],a.each("initialized beforeVisible visible hidden canceled accepted beforeClose".split(" "),function(b,c){a.isFunction(e[c])&&f.$el.bind(c+f.namespace,e[c])}),e.alwaysOpen&&(e.stayOpen=!0),a(document).bind("mousedown keyup touchstart checkkeyboard ".split(" ").join(f.namespace+" "),function(b){if(!f.opening){f.escClose(b);var c=a(b.target);if(c.hasClass(g.input)){var d=c.data("keyboard");d!==f||d.$el.hasClass(g.isCurrent)||b.type!==d.options.openOn||d.focusOn()}}}),f.$el.addClass(g.input+" "+e.css.input).attr({"aria-haspopup":"true",role:"textbox"}),(f.$el.is(":disabled")||f.$el.attr("readonly")&&!f.$el.hasClass(g.locked))&&f.$el.addClass(g.noKeyboard),e.openOn&&f.$el.bind(e.openOn+f.namespace,function(){f.focusOn()}),f.watermark||""!==f.$el.val()||""===f.inPlaceholder||""===f.$el.attr("placeholder")||f.$el.addClass(g.placeholder).val(f.inPlaceholder),f.$el.trigger(b.events.kbInit,[f,f.el]),e.alwaysOpen&&f.reveal()},f.toggle=function(){var a=f.$keyboard.find("."+b.css.keyToggle),c=!f.enabled;f.$preview.prop("readonly",c||f.options.lockInput),f.$keyboard.toggleClass(b.css.keyDisabled,c).find("."+b.css.keyButton).not(a).prop("disabled",c).attr("aria-disabled",c),a.toggleClass(b.css.keyDisabled,c),c&&f.typing_options&&(f.typing_options.text="")},f.setCurrent=function(){var c=b.css;a("."+c.hasFocus).removeClass(c.hasFocus),a("."+c.isCurrent).removeClass(c.isCurrent),f.$el.addClass(c.isCurrent),f.$keyboard.addClass(c.hasFocus),f.isCurrent(!0),f.isOpen=!0},f.isCurrent=function(a){var c=b.currentKeyboard||!1;return a?c=b.currentKeyboard=f.el:a===!1&&c===f.el&&(c=b.currentKeyboard=""),c===f.el},f.isVisible=function(){return f.$keyboard&&f.$keyboard.length?f.$keyboard.is(":visible"):!1},f.focusOn=function(){(f||!f.el.active)&&(f.$el.is(":visible")&&(f.timer2=setTimeout(function(){var a;/(number|email)/i.test(f.el.type)||e.caretToEnd||f.saveCaret(a,a,f.$el)},20)),f.isVisible()||(clearTimeout(f.timer),f.reveal()),e.alwaysOpen&&f.setCurrent())},f.reveal=function(c){f.isOpen&&(c=!0);var d=b.css;return f.opening=!0,a("."+d.keyboard).not("."+d.alwaysOpen).remove(),c&&(f.isOpen=!1,f.last.val=f.$preview&&f.$preview.val()||"",f.$keyboard.length&&(f.$keyboard.remove(),f.$keyboard=[],f.shiftActive=f.altActive=f.metaActive=!1)),f.$el.is(":disabled")||f.$el.attr("readonly")&&!f.$el.hasClass(d.locked)?void f.$el.addClass(d.noKeyboard):(f.$el.removeClass(d.noKeyboard),e.openOn&&f.$el.unbind(e.openOn+f.namespace),(!f.$keyboard||f.$keyboard&&(!f.$keyboard.length||a.contains(document.body,f.$keyboard[0])))&&f.startup(),f.watermark||f.el.value!==f.inPlaceholder||f.$el.removeClass(d.placeholder).val(""),f.originalContent=f.$el.val(),f.$preview.val(c?f.last.val:f.originalContent),e.acceptValid&&f.checkValid(),e.resetDefault&&(f.shiftActive=f.altActive=f.metaActive=!1,f.showSet()),f.$el.trigger(b.events.kbBeforeVisible,[f,f.el]),f.setCurrent(),f.toggle(),f.$keyboard.show(),e.usePreview&&b.msie&&("undefined"==typeof f.width&&(f.$preview.hide(),f.width=Math.ceil(f.$keyboard.width()),f.$preview.show()),f.$preview.width(f.width)),f.position=a.isEmptyObject(e.position)?!1:e.position,a.ui&&a.ui.position&&f.position&&(f.position.of=f.position.of||f.$el.data("keyboardPosition")||f.$el,f.position.collision=f.position.collision||"flipfit flipfit",e.position.at=e.usePreview?e.position.orig_at:e.position.at2,f.$keyboard.position(f.position)),f.checkDecimal(),f.lineHeight=parseInt(f.$preview.css("lineHeight"),10)||parseInt(f.$preview.css("font-size"),10)+4,e.caretToEnd&&f.saveCaret(f.originalContent.length,f.originalContent.length),b.allie&&(0===f.last.end&&f.last.start>0&&(f.last.end=f.last.start),f.last.start<0&&(f.last.start=f.last.end=f.originalContent.length)),f.timer2=setTimeout(function(){f.opening=!1,e.initialFocus&&b.caret(f.$preview,f.last),f.last.eventTime=(new Date).getTime(),f.$el.trigger(b.events.kbVisible,[f,f.el]),f.timer=setTimeout(function(){f&&f.saveCaret()},200)},10),f)},f.updateLanguage=function(){var c=b.layouts,d=e.language||c[e.layout]&&c[e.layout].lang&&c[e.layout].lang||[e.language||"en"],g=b.language;d=(a.isArray(d)?d[0]:d).split("-")[0],e.display=a.extend(!0,{},g.en.display,g[d]&&g[d].display||{},f.settings.display),e.combos=a.extend(!0,{},g.en.combos,g[d]&&g[d].combos||{},f.settings.combos),e.wheelMessage=g[d]&&g[d].wheelMessage||g.en.wheelMessage,e.rtl=c[e.layout]&&c[e.layout].rtl||g[d]&&g[d].rtl||!1,f.regex=g[d]&&g[d].comboRegex||b.comboRegex,f.decimal=/^\./.test(e.display.dec),f.$el.toggleClass("rtl",e.rtl).css("direction",e.rtl?"rtl":"")},f.startup=function(){var c=b.css;f.$preview=f.$el,f.$keyboard&&f.$keyboard.length||("custom"===e.layout&&(e.layoutHash="custom"+f.customHash()),f.layout="custom"===e.layout?e.layoutHash:e.layout,f.last.layout=f.layout,f.updateLanguage(),"undefined"==typeof b.builtLayouts[f.layout]&&(a.isFunction(e.create)?f.$keyboard=e.create(f):f.$keyboard.length||f.buildKeyboard(f.layout,!0)),f.$keyboard=b.builtLayouts[f.layout].$keyboard.clone(),""!==(f.el.id||"")&&f.$keyboard.attr("id",f.el.id+b.css.idSuffix),e.usePreview?(a.isEmptyObject(e.position)||(e.position.at=e.position.orig_at),f.$preview=f.$el.clone(!1).removeAttr("id").removeClass(c.placeholder+" "+c.input).addClass(c.preview+" "+e.css.input).removeAttr("aria-haspopup").attr("tabindex","-1").show(),"number"==f.$preview.attr("type")&&f.$preview.attr("type","text"),a("<div />").addClass(c.wrapper).append(f.$preview).prependTo(f.$keyboard)):a.isEmptyObject(e.position)||(e.position.at=e.position.at2)),f.preview=f.$preview[0],f.$decBtn=f.$keyboard.find("."+c.keyPrefix+"dec"),(e.enterNavigation||"TEXTAREA"===f.el.nodeName)&&f.alwaysAllowed.push(13),e.lockInput&&f.$preview.addClass(c.locked).attr({readonly:"readonly"}),f.bindKeyboard(),f.$keyboard.appendTo(e.appendLocally?f.$el.parent():e.appendTo||"body"),f.bindKeys(),e.reposition&&a.ui&&a.ui.position&&"body"==e.appendTo&&a(window).bind("resize"+f.namespace,function(){f.position&&f.isVisible()&&f.$keyboard.position(f.position)})},f.saveCaret=function(a,c,d){var e=b.caret(d||f.$preview,a,c);f.last.start="undefined"==typeof a?e.start:a,f.last.end="undefined"==typeof c?e.end:c},f.setScroll=function(){if(f.last.virtual){var a,b,c,d,g="TEXTAREA"===f.preview.nodeName,h=f.last.val.substring(0,Math.max(f.last.start,f.last.end));f.$previewCopy||(f.$previewCopy=f.$preview.clone().removeAttr("id").css({position:"absolute",left:0,zIndex:-10,visibility:"hidden"}).addClass("ui-keyboard-preview-clone"),g||f.$previewCopy.css({"white-space":"pre",width:0}),e.usePreview?f.$preview.after(f.$previewCopy):f.$keyboard.prepend(f.$previewCopy)),g?(f.$previewCopy.height(f.lineHeight).val(h),f.preview.scrollTop=f.lineHeight*(Math.floor(f.$previewCopy[0].scrollHeight/f.lineHeight)-1)):(f.$previewCopy.val(h.replace(/\s/g," ")),c=/c/i.test(e.scrollAdjustment)?f.preview.clientWidth/2:e.scrollAdjustment,a=f.$previewCopy[0].scrollWidth-1,"undefined"==typeof f.last.scrollWidth&&(f.last.scrollWidth=a,f.last.direction=!0),d=f.last.scrollWidth===a?f.last.direction:f.last.scrollWidth<a,b=f.preview.clientWidth-c,d?b>a?f.preview.scrollLeft=0:f.preview.scrollLeft=a-b:a>=f.preview.scrollWidth-b?f.preview.scrollLeft=f.preview.scrollWidth-c:a-c>0?f.preview.scrollLeft=a-c:f.preview.scrollLeft=0,f.last.scrollWidth=a,f.last.direction=d)}},f.bindKeyboard=function(){var c,d=b.builtLayouts[f.layout];f.$preview.unbind("keypress keyup keydown mouseup touchend ".split(" ").join(f.namespace+" ")).bind("click"+f.namespace,function(){f.timer2=setTimeout(function(){f.saveCaret()},150)}).bind("keypress"+f.namespace,function(g){if(e.lockInput)return!1;var h=g.charCode||g.which,i=f.last.key=String.fromCharCode(h);if(f.last.virtual=!1,f.last.event=g,f.last.$key=[],f.checkCaret&&f.saveCaret(),f.capsLock=h>=65&&90>=h&&!g.shiftKey||h>=97&&122>=h&&g.shiftKey?!0:!1,e.restrictInput){if((8===g.which||0===g.which)&&a.inArray(g.keyCode,f.alwaysAllowed))return;-1===a.inArray(h,d.acceptedKeys)&&(g.preventDefault(),c=a.extend({},g),c.type=b.events.inputRestricted,f.$el.trigger(c,[f,f.el]),a.isFunction(e.restricted)&&e.restricted(c,f,f.el))}else if((g.ctrlKey||g.metaKey)&&(97===g.which||99===g.which||118===g.which||g.which>=120&&g.which<=122))return;d.hasMappedKeys&&d.mappedKeys.hasOwnProperty(i)&&(f.last.key=d.mappedKeys[i],f.insertText(f.last.key),g.preventDefault()),f.checkMaxLength()}).bind("keyup"+f.namespace,function(c){switch(f.last.virtual=!1,c.which){case 9:if(f.tab&&e.tabNavigation&&!e.lockInput){f.shiftActive=c.shiftKey;var d=b.keyaction.tab(f);if(f.tab=!1,!d)return!1}else c.preventDefault();break;case 27:return e.ignoreEsc||f.close(e.autoAccept&&e.autoAcceptOnEsc?"true":!1),!1}return clearTimeout(f.throttled),f.throttled=setTimeout(function(){f.isVisible()&&f.checkCombos()},100),f.checkMaxLength(),f.$el.trigger(b.events.kbChange,[f,f.el]),f.last.val=f.$preview.val(),a.isFunction(e.change)?(e.change(a.Event(b.events.inputChange),f,f.el),!1):void 0}).bind("keydown"+f.namespace,function(a){if(9===a.which)return f.tab=!0,!1;if(e.lockInput)return!1;switch(f.last.virtual=!1,a.which){case 8:b.keyaction.bksp(f,null,a),a.preventDefault();break;case 13:b.keyaction.enter(f,null,a);break;case 20:f.shiftActive=f.capsLock=!f.capsLock,f.showSet();break;case 86:if(a.ctrlKey||a.metaKey){if(e.preventPaste)return void a.preventDefault();f.checkCombos()}}}).bind("mouseup touchend ".split(" ").join(f.namespace+" "),function(){f.last.virtual=!0,f.checkCaret&&f.saveCaret()}),f.$keyboard.bind("mousedown click touchstart ".split(" ").join(f.namespace+" "),function(b){b.stopPropagation(),f.isCurrent()||(f.reveal(),a(document).trigger("checkkeyboard"+f.namespace)),e.noFocus||f.$preview.focus()}),e.preventPaste&&(f.$preview.bind("contextmenu"+f.namespace,function(a){a.preventDefault()}),f.$el.bind("contextmenu"+f.namespace,function(a){a.preventDefault()}))},f.bindKeys=function(){var c=b.css;f.$allKeys=f.$keyboard.find("button."+c.keyButton).unbind(f.namespace+" "+f.namespace+"kb").bind(e.keyBinding.split(" ").join(f.namespace+" ")+f.namespace+" "+b.events.kbRepeater,function(d){if(d.preventDefault(),!f.$keyboard.is(":visible"))return!1;var g,h,i=f.last,j=this,k=a(j),l=(new Date).getTime();if(e.useWheel&&f.wheel&&(h=i.wheel_$Keys,k=h?h.eq(i.wheelIndex):k),g=k.attr("data-action"),g=":"===g?":":(g||"").split(":")[0],!(l-(i.eventTime||0)<e.preventDoubleEventTime)){if(i.eventTime=l,i.event=d,i.virtual=!0,e.noFocus||f.$preview.focus(),i.$key=k,i.key=k.attr("data-value"),f.checkCaret&&b.caret(f.$preview,i),g.match("meta")&&(g="meta"),g===i.key&&"string"==typeof b.keyaction[g])i.key=g=b.keyaction[g];else if(g in b.keyaction&&a.isFunction(b.keyaction[g])){if(b.keyaction[g](f,this,d)===!1)return!1;g=null}return"undefined"!=typeof g&&null!==g&&(i.key=a(this).hasClass(c.keyAction)?g:i.key,f.insertText(i.key),f.capsLock||e.stickyShift||d.shiftKey||(f.shiftActive=!1,f.showSet(k.attr("data-name")))),b.caret(f.$preview,i),f.checkCombos(),f.$el.trigger(b.events.kbChange,[f,f.el]),i.val=f.$preview.val(),a.isFunction(e.change)?(e.change(a.Event(b.events.inputChange),f,f.el),!1):void 0}}).bind("mouseenter mouseleave touchstart ".split(" ").join(f.namespace+" "),function(b){if(f.isCurrent()){var c,d,g=f.last,h=a(this),i=b.type;e.useWheel&&f.wheel&&(c=f.getLayers(h),d=(c.length?c.map(function(){return a(this).attr("data-value")||""}).get():"")||[h.text()],g.wheel_$Keys=c,g.wheelLayers=d,g.wheelIndex=a.inArray(h.attr("data-value"),d)),"mouseenter"!==i&&"touchstart"!==i||"password"===f.el.type||h.hasClass(e.css.buttonDisabled)||(h.addClass(e.css.buttonHover),e.useWheel&&f.wheel&&h.attr("title",function(a,b){return f.wheel&&""===b&&f.sets&&d.length>1&&"touchstart"!==i?e.wheelMessage:b})),"mouseleave"===i&&(h.removeClass("password"===f.el.type?"":e.css.buttonHover),e.useWheel&&f.wheel&&(g.wheelIndex=0,g.wheelLayers=[],g.wheel_$Keys=null,h.attr("title",function(a,b){return b===e.wheelMessage?"":b}).html(h.attr("data-html"))))}}).bind("mouseup"+f.namespace+" "+"mouseleave touchend touchmove touchcancel ".split(" ").join(f.namespace+"kb "),function(c){f.last.virtual=!0;var d,g=a(this);if("touchmove"===c.type){if(d=g.offset(),d.right=d.left+g.outerWidth(),d.bottom=d.top+g.outerHeight(),c.originalEvent.touches[0].pageX>=d.left&&c.originalEvent.touches[0].pageX<d.right&&c.originalEvent.touches[0].pageY>=d.top&&c.originalEvent.touches[0].pageY<d.bottom)return!0}else/(mouseleave|touchend|touchcancel)/i.test(c.type)?g.removeClass(e.css.buttonHover):(!e.noFocus&&f.isVisible()&&f.isCurrent()&&f.$preview.focus(),f.checkCaret&&b.caret(f.$preview,f.last));return f.mouseRepeat=[!1,""],clearTimeout(f.repeater),!1}).bind("click"+f.namespace,function(){return!1}).not("."+c.keyAction).bind("mousewheel"+f.namespace,function(b,c){if(e.useWheel&&f.wheel){c=c||b.deltaY;var d,g=f.last.wheelLayers||[];return g.length>1?(d=f.last.wheelIndex+(c>0?-1:1),d>g.length-1&&(d=0),0>d&&(d=g.length-1)):d=0,f.last.wheelIndex=d,a(this).html(g[d]),!1}}).add("."+c.keyPrefix+"tab bksp space enter".split(" ").join(",."+c.keyPrefix),f.$keyboard).bind("mousedown touchstart ".split(" ").join(f.namespace+"kb "),function(){if(0!==e.repeatRate){var b=a(this);f.mouseRepeat=[!0,b],setTimeout(function(){f.mouseRepeat[0]&&f.mouseRepeat[1]===b&&f.repeatKey(b)},e.repeatDelay)}return!1})},f.insertText=function(a){if("undefined"!=typeof a){var c,d,e="\b"===a,g=f.$preview.val(),h=b.caret(f.$preview),i=g.length;h.end<h.start&&(h.end=h.start),h.start>i&&(h.end=h.start=i),"TEXTAREA"===f.preview.nodeName&&b.msie&&"\n"===g.substr(h.start,1)&&(h.start+=1,h.end+=1),"{d}"===a&&(a="",d=h.start,h.end+=1),c=e&&h.start===h.end,a=e?"":a,g=g.substr(0,h.start-(c?1:0))+a+g.substr(h.end),d=h.start+(c?-1:a.length),f.$preview.val(g),f.saveCaret(d,d),f.setScroll()}},f.checkMaxLength=function(){var a,c,d=f.$preview.val();e.maxLength!==!1&&d.length>e.maxLength&&(a=b.caret(f.$preview).start,c=Math.min(a,e.maxLength),e.maxInsert||(d=f.last.val,c=a-1),f.$preview.val(d.substring(0,e.maxLength)),f.saveCaret(c,c)),f.$decBtn.length&&f.checkDecimal()},f.repeatKey=function(a){a.trigger(b.events.kbRepeater),f.mouseRepeat[0]&&(f.repeater=setTimeout(function(){f.repeatKey(a)},f.repeatTime))},f.showKeySet=function(a){"string"==typeof a?(f.last.keyset=[f.shiftActive,f.altActive,f.metaActive],f.shiftActive=/shift/i.test(a),f.altActive=/alt/i.test(a),/meta/.test(a)?(f.metaActive=!0,f.showSet(a.match(/meta\d+/i)[0])):(f.metaActive=!1,f.showSet())):f.showSet(a)},f.showSet=function(a){e=f.options;var c=b.css,d="",g=(f.shiftActive?1:0)+(f.altActive?2:0);return f.shiftActive||(f.capsLock=!1),f.metaActive?(d=/meta/i.test(a)?a:"",""===d?d=f.metaActive===!0?"":f.metaActive:f.metaActive=d,(!e.stickyShift&&f.last.keyset[2]!==f.metaActive||(f.shiftActive||f.altActive)&&!f.$keyboard.find("."+c.keySet+"-"+d+f.rows[g]).length)&&(f.shiftActive=f.altActive=!1)):!e.stickyShift&&f.last.keyset[2]!==f.metaActive&&f.shiftActive&&(f.shiftActive=f.altActive=!1),g=(f.shiftActive?1:0)+(f.altActive?2:0),d=0!==g||f.metaActive?""===d?"":"-"+d:"-normal",f.$keyboard.find("."+c.keySet+d+f.rows[g]).length?(f.$keyboard.find("."+c.keyPrefix+"alt,."+c.keyPrefix+"shift,."+c.keyAction+"[class*=meta]").removeClass(e.css.buttonActive).end().find("."+c.keyPrefix+"alt").toggleClass(e.css.buttonActive,f.altActive).end().find("."+c.keyPrefix+"shift").toggleClass(e.css.buttonActive,f.shiftActive).end().find("."+c.keyPrefix+"lock").toggleClass(e.css.buttonActive,f.capsLock).end().find("."+c.keySet).hide().end().find("."+c.keySet+d+f.rows[g]).show().end().find("."+c.keyAction+"."+c.keyPrefix+d).addClass(e.css.buttonActive),f.last.keyset=[f.shiftActive,f.altActive,f.metaActive],void f.$el.trigger(b.events.kbKeysetChange,[f,f.el])):(f.shiftActive=f.last.keyset[0],f.altActive=f.last.keyset[1],void(f.metaActive=f.last.keyset[2]))},f.checkCombos=function(){if(!f.isVisible())return f.$preview.val();var a,c,d,g,h=f.$preview.val(),i=b.caret(f.$preview),j=b.builtLayouts[f.layout],k=h.length;if(""===h)return h;if(i.end<i.start&&(i.end=i.start),i.start>k&&(i.end=i.start=k),b.msie&&"\n"===h.substr(i.start,1)&&(i.start+=1,i.end+=1),e.useCombos&&(b.msie?h=h.replace(f.regex,function(a,b,c){return e.combos.hasOwnProperty(b)?e.combos[b][c]||a:a}):f.$preview.length&&(d=i.start-(i.start-2>=0?2:0),b.caret(f.$preview,d,i.end),g=(b.caret(f.$preview).text||"").replace(f.regex,function(a,b,c){return e.combos.hasOwnProperty(b)?e.combos[b][c]||a:a}),f.$preview.val(b.caret(f.$preview).replaceStr(g)),h=f.$preview.val())),e.restrictInput&&""!==h){for(d=h,c=j.acceptedKeys.length,a=0;c>a;a++)""!==d&&(g=j.acceptedKeys[a],h.indexOf(g)>=0&&(/[\[|\]|\\|\^|\$|\.|\||\?|\*|\+|\(|\)|\{|\}]/g.test(g)&&(g="\\"+g),d=d.replace(new RegExp(g,"g"),"")));""!==d&&(h=h.replace(d,""))}return i.start+=h.length-k,i.end+=h.length-k,f.$preview.val(h),f.saveCaret(i.start,i.end),f.setScroll(),f.checkMaxLength(),e.acceptValid&&f.checkValid(),h},f.checkValid=function(){var c=b.css,d=!0;a.isFunction(e.validate)&&(d=e.validate(f,f.$preview.val(),!1)),f.$keyboard.find("."+c.keyPrefix+"accept").toggleClass(c.inputInvalid,!d).toggleClass(c.inputValid,d)},f.checkDecimal=function(){f.decimal&&/\./g.test(f.preview.value)||!f.decimal&&/\,/g.test(f.preview.value)?f.$decBtn.attr({disabled:"disabled","aria-disabled":"true"}).removeClass(e.css.buttonHover).addClass(e.css.buttonDisabled):f.$decBtn.removeAttr("disabled").attr({"aria-disabled":"false"}).addClass(e.css.buttonDefault).removeClass(e.css.buttonDisabled)},f.getLayers=function(c){var d=b.css,e=c.attr("data-pos"),f=c.closest("."+d.keyboard).find('button[data-pos="'+e+'"]');return f.filter(function(){return""!==a(this).find("."+d.keyText).text()}).add(c)},f.switchInput=function(b,c){if(a.isFunction(e.switchInput))e.switchInput(f,b,c);else{f.$keyboard.length&&f.$keyboard.hide();var d,g=!1,h=a("button, input, textarea, a").filter(":visible").not(":disabled"),i=h.index(f.$el)+(b?1:-1);if(f.$keyboard.length&&f.$keyboard.show(),i>h.length-1&&(g=e.stopAtEnd,i=0),0>i&&(g=e.stopAtEnd,i=h.length-1),!g){if(c=f.close(c),!c)return;d=h.eq(i).data("keyboard"),d&&d.options.openOn.length?d.focusOn():h.eq(i).focus()}}return!1},f.close=function(c){if(f.isOpen){clearTimeout(f.throttled);var d=b.css,g=b.events,h=c?f.checkCombos():f.originalContent;if(c&&a.isFunction(e.validate)&&!e.validate(f,h,!0)&&(h=f.originalContent,c=!1,e.cancelClose))return;f.isCurrent(!1),f.isOpen=!1,f.$preview.val(h),f.$el.removeClass(d.isCurrent+" "+d.inputAutoAccepted).addClass(c?c===!0?"":d.inputAutoAccepted:"").val(h).trigger(g.inputChange).trigger(e.alwaysOpen?"":g.kbBeforeClose,[f,f.el,c||!1]).trigger(c?g.inputAccepted:g.inputCanceled,[f,f.el]).trigger(e.alwaysOpen?g.kbInactive:g.kbHidden,[f,f.el]).blur(),f&&(f.last.eventTime=(new Date).getTime(),e.openOn&&(f.timer=setTimeout(function(){f&&f.el.active&&(f.$el.bind(e.openOn+f.namespace,function(){f.focusOn()}),a(":focus")[0]===f.el&&f.$el.blur())},500)),!e.alwaysOpen&&f.$keyboard&&(f.$keyboard.remove(),f.$keyboard=[]),f.watermark||""!==f.el.value||""===f.inPlaceholder||f.$el.addClass(d.placeholder).val(f.inPlaceholder))}return!!c},f.accept=function(){return f.close(!0)},f.escClose=function(c){if(c&&"keyup"===c.type)return 27!==c.which||e.ignoreEsc?"":f.close(e.autoAccept&&e.autoAcceptOnEsc?"true":!1);if(f.isOpen&&(!f.isCurrent()&&f.isOpen||f.isOpen&&c.target!==f.el)){if(e.stayOpen&&!a(c.target).hasClass("ui-keyboard-input"))return;b.allie&&c.preventDefault(),f.close(e.autoAccept?"true":!1)}},f.keyBtn=a("<button />").attr({role:"button",type:"button","aria-disabled":"false",tabindex:"-1"}).addClass(b.css.keyButton),f.processName=function(a){var b,c,d=(a||"").replace(/[^a-z0-9-_]/gi,""),e=d.length,f=[];if(e>1&&a===d)return a;if(e=a.length){for(b=0;e>b;b++)c=a[b],f.push(/[a-z0-9-_]/i.test(c)?/[-_]/.test(c)?"":c:(0===b?"":"-")+c.charCodeAt(0));return f.join("")}return a},f.addKey=function(c,d,g){var h,i,j,k,l=b.css,m=d.split(":"),n=m.length-1,o=g===!0?c:e.display[m[0]]||c,p={isAction:!g,action:c,name:f.processName(c.split(/[(:]/)[0])};return/\(.+\)/.test(o)&&(j=o.replace(/\(([^()]+)\)/,""),i=o.match(/\(([^()]+)\)/)[1],o=j,k=j.split(":"),j=""!==k[0]&&k.length>1?k[0]:j,b.builtLayouts[f.layout].mappedKeys[i]=j),k=o.split(":"),""===k[0]&&""===k[1]&&(o=":"),o=""!==k[0]&&k.length>1?k[0]:o,p.value=a.trim(g?o:m[1]||o),p.title=k.length>1?a.trim(k[1]).replace(/_/g," ")||"":n>0?m[n]||"":"",h=p.value.length>2?" "+l.keyWide:"",h+=g?"":" "+l.keyAction,p.html='<span class="'+l.keyText+'">'+p.value.replace(/[\u00A0-\u9999<>\&]/gim,function(a){return"&#"+a.charCodeAt(0)+";"})+"</span>",p.$key=f.keyBtn.clone().attr({"data-value":p.value,"data-name":p.name,"data-pos":f.temp[1]+","+f.temp[2],title:p.title,"data-action":p.action,"data-html":p.html}).addClass((""===p.name?"":l.keyPrefix+p.name+h+" ")+e.css.buttonDefault).html(p.html).appendTo(f.temp[0]),"function"==typeof e.buildKey&&(p=e.buildKey(f,p),m=p.$key.html(),p.$key.attr("data-html",m)),p.$key},f.customHash=function(a){var b,c,d,f,g,h=[],i=[];a="undefined"==typeof a?e.customLayout:a;for(c in a)a.hasOwnProperty(c)&&h.push(a[c]);if(i=i.concat.apply(i,h).join(" "),d=0,g=i.length,0===g)return d;for(b=0;g>b;b++)f=i.charCodeAt(b),d=(d<<5)-d+f,d&=d;return d},f.buildKeyboard=function(c,d){a.isEmptyObject(e.display)&&f.updateLanguage();var g,h,i,j=b.css,k=0,l=b.builtLayouts[c||f.layout||e.layout]={mappedKeys:{},acceptedKeys:[]},m=l.acceptedKeys=[],n=j.keyboard+" "+e.css.popup+" "+e.css.container+(e.alwaysOpen?" "+j.alwaysOpen:""),o=a("<div />").addClass(n).attr({role:"textbox"}).hide();return d&&"custom"===e.layout||!b.layouts.hasOwnProperty(e.layout)?(e.layout="custom",n=b.layouts.custom=e.customLayout||{normal:["{cancel}"]}):n=b.layouts[d?e.layout:c||f.layout||e.layout],a.each(n,function(b,c){if(""!==b&&!/^(name|lang|rtl)$/i.test(b))for("default"===b&&(b="normal"),k++,h=a("<div />").attr("name",b).addClass(j.keySet+" "+j.keySet+"-"+b).appendTo(o).toggle("normal"===b),g=0;g<c.length;g++)i=a.trim(c[g]).replace(/\{(\.?)[\s+]?:[\s+]?(\.?)\}/g,"{$1:$2}"),f.buildRow(h,g,i.split(/\s+/),m),h.find("."+j.keyButton+":last").after('<br class="'+j.endRow+'"/>')}),k>1&&(f.sets=!0),l.hasMappedKeys=!a.isEmptyObject(l.mappedKeys),l.$keyboard=o,o},f.buildRow=function(c,d,g,h){var i,j,k,l,m,n,o=b.css;for(k=0;k<g.length;k++)if(f.temp=[c,d,k],l=!1,0!==g[k].length)if(/^\{\S+\}$/.test(g[k])){if(m=g[k].match(/^\{(\S+)\}$/)[1],/\!\!/.test(m)&&(m=m.replace("!!",""),l=!0),/^sp:((\d+)?([\.|,]\d+)?)(em|px)?$/i.test(m)&&(n=parseFloat(m.replace(/,/,".").match(/^sp:((\d+)?([\.|,]\d+)?)(em|px)?$/i)[1]||0),a('<span class="'+o.keyText+'"></span>').width(m.match(/px/i)?n+"px":2*n+"em").addClass(o.keySpacer).appendTo(c)),/^empty(:((\d+)?([\.|,]\d+)?)(em|px)?)?$/i.test(m)&&(n=/:/.test(m)?parseFloat(m.replace(/,/,".").match(/^empty:((\d+)?([\.|,]\d+)?)(em|px)?$/i)[1]||0):"",f.addKey(""," ").addClass(e.css.buttonDisabled+" "+e.css.buttonEmpty).attr("aria-disabled",!0).width(n?m.match("px")?n+"px":2*n+"em":"")),/^meta\d+\:?(\w+)?/i.test(m)){f.addKey(m.split(":")[0],m).addClass(o.keyHasActive);continue}switch(j=m.split(":"),j[0].toLowerCase()){case"a":case"accept":f.addKey("accept",m).addClass(e.css.buttonAction+" "+o.keyAction);break;case"alt":case"altgr":f.addKey("alt",m).addClass(o.keyHasActive);break;case"b":case"bksp":f.addKey("bksp",m);break;case"c":case"cancel":f.addKey("cancel",m).addClass(e.css.buttonAction+" "+o.keyAction);break;case"combo":f.addKey("combo",m).addClass(o.keyHasActive).toggleClass(e.css.buttonActive,e.useCombos);break;case"dec":h.push(f.decimal?".":","),f.addKey("dec",m);break;case"e":case"enter":f.addKey("enter",m).addClass(e.css.buttonAction+" "+o.keyAction);break;case"lock":f.addKey("lock",m).addClass(o.keyHasActive);break;case"s":case"shift":f.addKey("shift",m).addClass(o.keyHasActive);break;case"sign":h.push("-"),f.addKey("sign",m);break;case"space":h.push(" "),f.addKey("space",m);break;case"t":case"tab":f.addKey("tab",m);break;default:b.keyaction.hasOwnProperty(j[0])&&f.addKey(j[0],m).toggleClass(e.css.buttonAction+" "+o.keyAction,l)}}else i=g[k],h.push(":"===i?i:i.split(":")[0]),f.addKey(i,i,!0)},f.removeBindings=function(b){a(document).unbind(b),a(window).unbind(b),f.$el.unbind(b)},f.destroy=function(a){var c,d=b.css,g=f.extensionNamespace.length,h=[d.input,d.locked,d.placeholder,d.noKeyboard,d.alwaysOpen,e.css.input].join(" ");for(clearTimeout(f.timer),clearTimeout(f.timer2),f.removeBindings(f.namespace),c=0;g>c;c++)f.removeBindings(f.extensionNamespace[c]);f.el.active=!1,f.$keyboard.length&&f.$keyboard.remove(),f.$el.removeClass(h).removeAttr("aria-haspopup").removeAttr("role").removeData("keyboard"),f=null,"function"==typeof a&&a()},f.init()};return b.css={idSuffix:"_keyboard",input:"ui-keyboard-input",wrapper:"ui-keyboard-preview-wrapper",preview:"ui-keyboard-preview",keyboard:"ui-keyboard",keySet:"ui-keyboard-keyset",keyButton:"ui-keyboard-button",keyWide:"ui-keyboard-widekey",keyPrefix:"ui-keyboard-",keyText:"ui-keyboard-text",keyHasActive:"ui-keyboard-hasactivestate",keyAction:"ui-keyboard-actionkey",keySpacer:"ui-keyboard-spacer",keyToggle:"ui-keyboard-toggle",keyDisabled:"ui-keyboard-disabled",locked:"ui-keyboard-lockedinput",alwaysOpen:"ui-keyboard-always-open",noKeyboard:"ui-keyboard-nokeyboard",placeholder:"ui-keyboard-placeholder",hasFocus:"ui-keyboard-has-focus",isCurrent:"ui-keyboard-input-current",inputValid:"ui-keyboard-valid-input",inputInvalid:"ui-keyboard-invalid-input",inputAutoAccepted:"ui-keyboard-autoaccepted",endRow:"ui-keyboard-button-endrow"},b.events={kbChange:"keyboardChange",kbBeforeClose:"beforeClose",kbBeforeVisible:"beforeVisible",kbVisible:"visible",kbInit:"initialized",kbInactive:"inactive",kbHidden:"hidden",kbRepeater:"repeater",kbKeysetChange:"keysetChange",inputAccepted:"accepted",inputCanceled:"canceled",inputChange:"change",inputRestricted:"restricted"},b.keyaction={accept:function(a){return a.close(!0),!1},alt:function(a){a.altActive=!a.altActive,a.showSet()},bksp:function(a){a.insertText("\b")},cancel:function(a){return a.close(),!1},clear:function(a){a.$preview.val(""),a.$decBtn.length&&a.checkDecimal()},combo:function(a){var c=!a.options.useCombos;return a.options.useCombos=c,a.$keyboard.find("."+b.css.keyPrefix+"combo").toggleClass(a.options.css.buttonActive,c),c&&a.checkCombos(),!1},dec:function(a){a.insertText(a.decimal?".":",")},del:function(a){a.insertText("{d}")},"default":function(a){a.shiftActive=a.altActive=a.metaActive=!1,a.showSet()},enter:function(b,c,d){var e=b.el.nodeName,f=b.options;return d.shiftKey?f.enterNavigation?b.switchInput(!d[f.enterMod],!0):b.close(!0):f.enterNavigation&&("TEXTAREA"!==e||d[f.enterMod])?b.switchInput(!d[f.enterMod],f.autoAccept?"true":!1):void("TEXTAREA"===e&&a(d.target).closest("button").length&&b.insertText(" \n"))},lock:function(a){a.last.keyset[0]=a.shiftActive=a.capsLock=!a.capsLock,a.showSet()},left:function(a){var c=b.caret(a.$preview);c.start-1>=0&&(a.last.start=a.last.end=c.start-1,b.caret(a.$preview,a.last),a.setScroll())},meta:function(b,c){var d=a(c);b.metaActive=!d.hasClass(b.options.css.buttonActive),b.showSet(d.attr("data-name"))},next:function(a){return a.switchInput(!0,a.options.autoAccept),!1},normal:function(a){a.shiftActive=a.altActive=a.metaActive=!1,a.showSet()},prev:function(a){return a.switchInput(!1,a.options.autoAccept),!1},right:function(a){var c=b.caret(a.$preview);c.start+1<=a.$preview.val().length&&(a.last.start=a.last.end=c.start+1,b.caret(a.$preview,a.last),a.setScroll())},shift:function(a){a.last.keyset[0]=a.shiftActive=!a.shiftActive,a.showSet()},sign:function(a){/^\-?\d*\.?\d*$/.test(a.$preview.val())&&a.$preview.val(-1*a.$preview.val())},space:function(a){a.insertText(" ")},tab:function(a){var b=a.el.nodeName,c=a.options;return"INPUT"===b?c.tabNavigation?a.switchInput(!a.shiftActive,!0):!1:void a.insertText(" ")},toggle:function(a){a.enabled=!a.enabled,a.toggle()},NBSP:" ",ZWSP:"",ZWNJ:"",ZWJ:"",LRM:"",RLM:""},b.builtLayouts={},b.layouts={alpha:{normal:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} a b c d e f g h i j [ ] \\","k l m n o p q r s ; ' {enter}","{shift} t u v w x y z , . / {shift}","{accept} {space} {cancel}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} A B C D E F G H I J { } |",'K L M N O P Q R S : " {enter}',"{shift} T U V W X Y Z < > ? {shift}","{accept} {space} {cancel}"]},qwerty:{normal:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w e r t y u i o p [ ] \\","a s d f g h j k l ; ' {enter}","{shift} z x c v b n m , . / {shift}","{accept} {space} {cancel}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W E R T Y U I O P { } |",'A S D F G H J K L : " {enter}',"{shift} Z X C V B N M < > ? {shift}","{accept} {space} {cancel}"]},international:{normal:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w e r t y u i o p [ ] \\","a s d f g h j k l ; ' {enter}","{shift} z x c v b n m , . / {shift}","{accept} {alt} {space} {alt} {cancel}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W E R T Y U I O P { } |",'A S D F G H J K L : " {enter}',"{shift} Z X C V B N M < > ? {shift}","{accept} {alt} {space} {alt} {cancel}"],alt:["~ ¡ ² ³ ¤ € ¼ ½ ¾ ‘ ’ ¥ × {bksp}","{tab} ä å é ® þ ü ú í ó ö « » ¬","á ß ð f g h j k ø ¶ ´ {enter}","{shift} æ x © v b ñ µ ç > ¿ {shift}","{accept} {alt} {space} {alt} {cancel}"],"alt-shift":["~ ¹ ² ³ £ € ¼ ½ ¾ ‘ ’ ¥ ÷ {bksp}","{tab} Ä Å É ® Þ Ü Ú Í Ó Ö « » ¦","Ä § Ð F G H J K Ø ° ¨ {enter}","{shift} Æ X ¢ V B Ñ µ Ç . ¿ {shift}","{accept} {alt} {space} {alt} {cancel}"]},colemak:{normal:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w f p g j l u y ; [ ] \\","{bksp} a r s t d h n e i o ' {enter}","{shift} z x c v b k m , . / {shift}","{accept} {space} {cancel}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W F P G J L U Y : { } |",'{bksp} A R S T D H N E I O " {enter}',"{shift} Z X C V B K M < > ? {shift}","{accept} {space} {cancel}"]},dvorak:{normal:["` 1 2 3 4 5 6 7 8 9 0 [ ] {bksp}","{tab} ' , . p y f g c r l / = \\","a o e u i d h t n s - {enter}","{shift} ; q j k x b m w v z {shift}","{accept} {space} {cancel}"],shift:["~ ! @ # $ % ^ & * ( ) { } {bksp}",'{tab} " < > P Y F G C R L ? + |',"A O E U I D H T N S _ {enter}","{shift} : Q J K X B M W V Z {shift}","{accept} {space} {cancel}"]},num:{normal:["= ( ) {b}","{clear} / * -","7 8 9 +","4 5 6 {sign}","1 2 3 %","0 {dec} {a} {c}"]}},b.language=a.extend({},b.language,{en:{display:{a:"✔:Accept (Shift+Enter)",accept:"Accept:Accept (Shift+Enter)",alt:"Alt:⌥ AltGr",b:"⌫:Backspace",bksp:"Bksp:Backspace",c:"✖:Cancel (Esc)",cancel:"Cancel:Cancel (Esc)",clear:"C:Clear",combo:"ö:Toggle Combo Keys",dec:".:Decimal",e:"⏎:Enter",empty:" ",enter:"Enter:Enter ⏎",left:"←",lock:"Lock:⇪ Caps Lock",next:"Next ⇨",prev:"⇦ Prev",right:"→",s:"⇧:Shift",shift:"Shift:Shift",sign:"±:Change Sign",space:" :Space",t:"⇥:Tab",tab:"⇥ Tab:Tab",toggle:" "},wheelMessage:"Use mousewheel to see other keys",comboRegex:/([`\'~\^\"ao])([a-z])/gim,combos:{"`":{a:"à",A:"À",e:"è",E:"È",i:"ì",I:"Ì",o:"ò",O:"Ò",
u:"ù",U:"Ù",y:"ỳ",Y:"Ỳ"},"'":{a:"á",A:"Á",e:"é",E:"É",i:"í",I:"Í",o:"ó",O:"Ó",u:"ú",U:"Ú",y:"ý",Y:"Ý"},'"':{a:"ä",A:"Ä",e:"ë",E:"Ë",i:"ï",I:"Ï",o:"ö",O:"Ö",u:"ü",U:"Ü",y:"ÿ",Y:"Ÿ"},"^":{a:"â",A:"Â",e:"ê",E:"Ê",i:"î",I:"Î",o:"ô",O:"Ô",u:"û",U:"Û",y:"ŷ",Y:"Ŷ"},"~":{a:"ã",A:"Ã",e:"ẽ",E:"Ẽ",i:"ĩ",I:"Ĩ",o:"õ",O:"Õ",u:"ũ",U:"Ũ",y:"ỹ",Y:"Ỹ",n:"ñ",N:"Ñ"}}}}),b.defaultOptions={language:null,rtl:!1,layout:"qwerty",customLayout:null,position:{of:null,my:"center top",at:"center top",at2:"center bottom"},reposition:!0,usePreview:!0,alwaysOpen:!1,initialFocus:!0,noFocus:!1,stayOpen:!1,ignoreEsc:!1,css:{input:"ui-widget-content ui-corner-all",container:"ui-widget-content ui-widget ui-corner-all ui-helper-clearfix",popup:"",buttonDefault:"ui-state-default ui-corner-all",buttonHover:"ui-state-hover",buttonAction:"ui-state-active",buttonActive:"ui-state-active",buttonDisabled:"ui-state-disabled",buttonEmpty:"ui-keyboard-empty"},autoAccept:!1,autoAcceptOnEsc:!1,lockInput:!1,restrictInput:!1,acceptValid:!1,cancelClose:!0,tabNavigation:!1,enterNavigation:!1,enterMod:"altKey",stopAtEnd:!0,appendLocally:!1,appendTo:"body",stickyShift:!0,preventPaste:!1,caretToEnd:!1,scrollAdjustment:10,maxLength:!1,maxInsert:!0,repeatDelay:500,repeatRate:20,resetDefault:!1,openOn:"focus",keyBinding:"mousedown touchstart",useWheel:!0,useCombos:!0,validate:function(a,b,c){return!0}},b.comboRegex=/([`\'~\^\"ao])([a-z])/gim,b.currentKeyboard="",a('<!--[if lte IE 8]><script>jQuery("body").addClass("oldie");</script><![endif]--><!--[if IE]><script>jQuery("body").addClass("ie");</script><![endif]-->').appendTo("body").remove(),b.msie=a("body").hasClass("oldie"),b.allie=a("body").hasClass("ie"),b.watermark="undefined"!=typeof document.createElement("input").placeholder,b.checkCaretSupport=function(){if("boolean"!=typeof b.checkCaret){var c=a('<div style="height:0px;width:0px;overflow:hidden;"><input type="text" value="testing"/></div>').prependTo("body");b.caret(c.find("input"),3,3),b.checkCaret=3!==b.caret(c.find("input").hide().show()).start,c.remove()}return b.checkCaret},b.caret=function(a,b,c){if(!a.length||a.is(":hidden")||"hidden"===a.css("visibility"))return{};var d,e,f,g,h=a.getkeyboard()&&a.getkeyboard().options.noFocus;return h||a.focus(),"undefined"!=typeof b?("object"==typeof b&&"start"in b&&"end"in b?(d=b.start,e=b.end):"undefined"==typeof c&&(c=b),"number"==typeof b&&"number"==typeof c?(d=b,e=c):"start"===b?d=e=0:"string"==typeof b&&(d=e=a.val().length),a.caret(d,e,h)):(g=a.caret(),d=g.start,e=g.end,f=a[0].value||a.text()||"",{start:d,end:e,text:f.substring(d,e),replaceStr:function(a){return f.substring(0,d)+a+f.substring(e,f.length)}})},a.fn.keyboard=function(b){return this.each(function(){a(this).data("keyboard")||new a.keyboard(this,b)})},a.fn.getkeyboard=function(){return this.data("keyboard")},a.fn.caret=function(a,b,c){if("undefined"==typeof this[0]||this.is(":hidden")||"hidden"===this.css("visibility"))return this;var d,e,f,g,h,i=document.selection,j=this,k=j[0],l=k.scrollTop,m=!1,n=!0;try{m="selectionStart"in k}catch(o){n=!1}return n&&"undefined"!=typeof a?(/(email|number)/i.test(k.type)||(m?(k.selectionStart=a,k.selectionEnd=b):(d=k.createTextRange(),d.collapse(!0),d.moveStart("character",a),d.moveEnd("character",b-a),d.select())),c||!j.is(":visible")&&"hidden"===j.css("visibility")||k.focus(),k.scrollTop=l,this):(/(email|number)/i.test(k.type)?a=b=j.val().length:m?(a=k.selectionStart,b=k.selectionEnd):i?"TEXTAREA"===k.nodeName?(h=j.val(),e=i.createRange(),f=e.duplicate(),f.moveToElementText(k),f.setEndPoint("EndToEnd",e),a=f.text.replace(/\r/g,"\n").length,b=a+e.text.replace(/\r/g,"\n").length):(h=j.val().replace(/\r/g,"\n"),e=i.createRange().duplicate(),e.moveEnd("character",h.length),a=""===e.text?h.length:h.lastIndexOf(e.text),e=i.createRange().duplicate(),e.moveStart("character",-h.length),b=e.text.length):a=b=(k.value||"").length,g=k.value||"",{start:a,end:b,text:g.substring(a,b),replace:function(c){return g.substring(0,a)+c+g.substring(b,g.length)}})},b}); | ahocevar/cdnjs | ajax/libs/virtual-keyboard/1.25.0/js/jquery.keyboard.min.js | JavaScript | mit | 36,253 |
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery","angular","./jquery.fileupload-image","./jquery.fileupload-audio","./jquery.fileupload-video","./jquery.fileupload-validate"],e):"object"==typeof exports?e(require("jquery"),require("angular"),require("./jquery.fileupload-image"),require("./jquery.fileupload-audio"),require("./jquery.fileupload-video"),require("./jquery.fileupload-validate")):e()}(function(){"use strict";angular.module("blueimp.fileupload",[]).provider("fileUpload",function(){var e,o=function(e){angular.element(this).fileupload("option","scope").$evalAsync(e)},t=function(e,r){var o=r.files,n=o[0];angular.forEach(o,function(e,o){e._index=o,e.$state=function(){return r.state()},e.$processing=function(){return r.processing()},e.$progress=function(){return r.progress()},e.$response=function(){return r.response()}}),n.$submit=function(){if(!n.error)return r.submit()},n.$cancel=function(){return r.abort()}};e=this.defaults={handleResponse:function(e,o){var r=o.result&&o.result.files;r?o.scope.replace(o.files,r):(o.errorThrown||"error"===o.textStatus)&&(o.files[0].error=o.errorThrown||o.textStatus)},add:function(e,o){if(e.isDefaultPrevented())return!1;var r=o.scope,n=[];angular.forEach(o.files,function(e){n.push(e)}),r.$parent.$applyAsync(function(){t(0,o);var e=r.option("prependFiles")?"unshift":"push";Array.prototype[e].apply(r.queue,o.files)}),o.process(function(){return r.process(o)}).always(function(){r.$parent.$applyAsync(function(){t(0,o),r.replace(n,o.files)})}).then(function(){(r.option("autoUpload")||o.autoUpload)&&!1!==o.autoUpload&&o.submit()})},done:function(e,o){if(e.isDefaultPrevented())return!1;var r=this;o.scope.$apply(function(){o.handleResponse.call(r,e,o)})},fail:function(e,o){if(e.isDefaultPrevented())return!1;var r=this,n=o.scope;"abort"!==o.errorThrown?n.$apply(function(){o.handleResponse.call(r,e,o)}):n.clear(o.files)},stop:o,processstart:o,processstop:o,getNumberOfFiles:function(){var e=this.scope;return e.queue.length-e.processing()},dataType:"json",autoUpload:!1},this.$get=[function(){return{defaults:e}}]}).provider("formatFileSizeFilter",function(){var l={units:[{size:1e9,suffix:" GB"},{size:1e6,suffix:" MB"},{size:1e3,suffix:" KB"}]};this.defaults=l,this.$get=function(){return function(e){if(!angular.isNumber(e))return"";for(var o,r,n=!0,t=0;n;){if(o=(n=l.units[t]).prefix||"",r=n.suffix||"",t===l.units.length-1||e>=n.size)return o+(e/n.size).toFixed(2)+r;t+=1}}}}).controller("FileUploadController",["$scope","$element","$attrs","$window","fileUpload","$q",function(r,n,e,o,t,l){var i={progress:function(){return n.fileupload("progress")},active:function(){return n.fileupload("active")},option:function(e,o){if(1===arguments.length)return n.fileupload("option",e);n.fileupload("option",e,o)},add:function(e){return n.fileupload("add",e)},send:function(e){return n.fileupload("send",e)},process:function(e){return n.fileupload("process",e)},processing:function(e){return n.fileupload("processing",e)}};r.disabled=!o.jQuery.support.fileInput,r.queue=r.queue||[],r.clear=function(e){var o=this.queue,r=o.length,n=e,t=1;for(angular.isArray(e)&&(n=e[0],t=e.length);r;)if(o[r-=1]===n)return o.splice(r,t)},r.replace=function(e,o){var r,n,t=this.queue,l=e[0];for(r=0;r<t.length;r+=1)if(t[r]===l){for(n=0;n<o.length;n+=1)t[r+n]=o[n];return}},r.applyOnQueue=function(e){var o,r,n=this.queue.slice(0),t=[];for(o=0;o<n.length;o+=1)(r=n[o])[e]&&t.push(r[e]());return l.all(t)},r.submit=function(){return this.applyOnQueue("$submit")},r.cancel=function(){return this.applyOnQueue("$cancel")},angular.extend(r,i),n.fileupload(angular.extend({scope:r},t.defaults)).on("fileuploadadd",function(e,o){o.scope=r}).on("fileuploadfail",function(e,o){if("abort"!==o.errorThrown&&o.dataType&&o.dataType.indexOf("json")===o.dataType.length-4)try{o.result=angular.fromJson(o.jqXHR.responseText)}catch(e){}}).on(["fileuploadadd","fileuploadsubmit","fileuploadsend","fileuploaddone","fileuploadfail","fileuploadalways","fileuploadprogress","fileuploadprogressall","fileuploadstart","fileuploadstop","fileuploadchange","fileuploadpaste","fileuploaddrop","fileuploaddragover","fileuploadchunkbeforesend","fileuploadchunksend","fileuploadchunkdone","fileuploadchunkfail","fileuploadchunkalways","fileuploadprocessstart","fileuploadprocess","fileuploadprocessdone","fileuploadprocessfail","fileuploadprocessalways","fileuploadprocessstop"].join(" "),function(e,o){r.$parent.$applyAsync(function(){r.$emit(e.type,o).defaultPrevented&&e.preventDefault()})}).on("remove",function(){var e;for(e in i)i.hasOwnProperty(e)&&delete r[e]}),r.$watch(e.fileUpload,function(e){e&&n.fileupload("option",e)})}]).controller("FileUploadProgressController",["$scope","$attrs","$parse",function(o,e,r){var n=r(e.fileUploadProgress),t=function(){var e=n(o);e&&e.total&&(o.num=Math.floor(e.loaded/e.total*100))};t(),o.$watch(e.fileUploadProgress+".loaded",function(e,o){e!==o&&t()})}]).controller("FileUploadPreviewController",["$scope","$element","$attrs",function(e,o,r){e.$watch(r.fileUploadPreview+".preview",function(e){o.empty(),e&&o.append(e)})}]).directive("fileUpload",function(){return{controller:"FileUploadController",scope:!0}}).directive("fileUploadProgress",function(){return{controller:"FileUploadProgressController",scope:!0}}).directive("fileUploadPreview",function(){return{controller:"FileUploadPreviewController"}}).directive("download",function(){return function(e,o){o.on("dragstart",function(e){try{e.originalEvent.dataTransfer.setData("DownloadURL",["application/octet-stream",o.prop("download"),o.prop("href")].join(":"))}catch(e){}})}})}); | extend1994/cdnjs | ajax/libs/blueimp-file-upload/9.23.0/js/jquery.fileupload-angular.min.js | JavaScript | mit | 5,627 |
# This class is inherited by the has_one and belongs_to association classes
module ActiveRecord::Associations::Builder # :nodoc:
class SingularAssociation < Association #:nodoc:
def self.valid_options(options)
super + [:foreign_type, :dependent, :primary_key, :inverse_of, :required]
end
def self.define_accessors(model, reflection)
super
mixin = model.generated_association_methods
name = reflection.name
define_constructors(mixin, name) if reflection.constructable?
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
def reload_#{name}
association(:#{name}).force_reload_reader
end
CODE
end
# Defines the (build|create)_association methods for belongs_to or has_one association
def self.define_constructors(mixin, name)
mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
def build_#{name}(*args, &block)
association(:#{name}).build(*args, &block)
end
def create_#{name}(*args, &block)
association(:#{name}).create(*args, &block)
end
def create_#{name}!(*args, &block)
association(:#{name}).create!(*args, &block)
end
CODE
end
end
end
| ngpestelos/rails | activerecord/lib/active_record/associations/builder/singular_association.rb | Ruby | mit | 1,229 |
<?php
namespace Sabre\DAV\PartialUpdate;
use Sabre\DAV;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;
/**
* Partial update plugin (Patch method)
*
* This plugin provides a way to modify only part of a target resource
* It may bu used to update a file chunk, upload big a file into smaller
* chunks or resume an upload.
*
* $patchPlugin = new \Sabre\DAV\PartialUpdate\Plugin();
* $server->addPlugin($patchPlugin);
*
* @copyright Copyright (C) fruux GmbH (https://fruux.com/)
* @author Jean-Tiare LE BIGOT (http://www.jtlebi.fr/)
* @license http://sabre.io/license/ Modified BSD License
*/
class Plugin extends DAV\ServerPlugin {
const RANGE_APPEND = 1;
const RANGE_START = 2;
const RANGE_END = 3;
/**
* Reference to server
*
* @var DAV\Server
*/
protected $server;
/**
* Initializes the plugin
*
* This method is automatically called by the Server class after addPlugin.
*
* @param DAV\Server $server
* @return void
*/
function initialize(DAV\Server $server) {
$this->server = $server;
$server->on('method:PATCH', [$this, 'httpPatch']);
}
/**
* Returns a plugin name.
*
* Using this name other plugins will be able to access other plugins
* using DAV\Server::getPlugin
*
* @return string
*/
function getPluginName() {
return 'partialupdate';
}
/**
* Use this method to tell the server this plugin defines additional
* HTTP methods.
*
* This method is passed a uri. It should only return HTTP methods that are
* available for the specified uri.
*
* We claim to support PATCH method (partirl update) if and only if
* - the node exist
* - the node implements our partial update interface
*
* @param string $uri
* @return array
*/
function getHTTPMethods($uri) {
$tree = $this->server->tree;
if ($tree->nodeExists($uri)) {
$node = $tree->getNodeForPath($uri);
if ($node instanceof IPatchSupport) {
return ['PATCH'];
}
}
return [];
}
/**
* Returns a list of features for the HTTP OPTIONS Dav: header.
*
* @return array
*/
function getFeatures() {
return ['sabredav-partialupdate'];
}
/**
* Patch an uri
*
* The WebDAV patch request can be used to modify only a part of an
* existing resource. If the resource does not exist yet and the first
* offset is not 0, the request fails
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @return void
*/
function httpPatch(RequestInterface $request, ResponseInterface $response) {
$path = $request->getPath();
// Get the node. Will throw a 404 if not found
$node = $this->server->tree->getNodeForPath($path);
if (!$node instanceof IPatchSupport) {
throw new DAV\Exception\MethodNotAllowed('The target resource does not support the PATCH method.');
}
$range = $this->getHTTPUpdateRange($request);
if (!$range) {
throw new DAV\Exception\BadRequest('No valid "X-Update-Range" found in the headers');
}
$contentType = strtolower(
$request->getHeader('Content-Type')
);
if ($contentType != 'application/x-sabredav-partialupdate') {
throw new DAV\Exception\UnsupportedMediaType('Unknown Content-Type header "' . $contentType . '"');
}
$len = $this->server->httpRequest->getHeader('Content-Length');
if (!$len) throw new DAV\Exception\LengthRequired('A Content-Length header is required');
switch ($range[0]) {
case self::RANGE_START :
// Calculate the end-range if it doesn't exist.
if (!$range[2]) {
$range[2] = $range[1] + $len - 1;
} else {
if ($range[2] < $range[1]) {
throw new DAV\Exception\RequestedRangeNotSatisfiable('The end offset (' . $range[2] . ') is lower than the start offset (' . $range[1] . ')');
}
if ($range[2] - $range[1] + 1 != $len) {
throw new DAV\Exception\RequestedRangeNotSatisfiable('Actual data length (' . $len . ') is not consistent with begin (' . $range[1] . ') and end (' . $range[2] . ') offsets');
}
}
break;
}
if (!$this->server->emit('beforeWriteContent', [$path, $node, null]))
return;
$body = $this->server->httpRequest->getBody();
$etag = $node->patch($body, $range[0], isset($range[1]) ? $range[1] : null);
$this->server->emit('afterWriteContent', [$path, $node]);
$response->setHeader('Content-Length', '0');
if ($etag) $response->setHeader('ETag', $etag);
$response->setStatus(204);
// Breaks the event chain
return false;
}
/**
* Returns the HTTP custom range update header
*
* This method returns null if there is no well-formed HTTP range request
* header. It returns array(1) if it was an append request, array(2,
* $start, $end) if it's a start and end range, lastly it's array(3,
* $endoffset) if the offset was negative, and should be calculated from
* the end of the file.
*
* Examples:
*
* null - invalid
* [1] - append
* [2,10,15] - update bytes 10, 11, 12, 13, 14, 15
* [2,10,null] - update bytes 10 until the end of the patch body
* [3,-5] - update from 5 bytes from the end of the file.
*
* @param RequestInterface $request
* @return array|null
*/
function getHTTPUpdateRange(RequestInterface $request) {
$range = $request->getHeader('X-Update-Range');
if (is_null($range)) return null;
// Matching "Range: bytes=1234-5678: both numbers are optional
if (!preg_match('/^(append)|(?:bytes=([0-9]+)-([0-9]*))|(?:bytes=(-[0-9]+))$/i', $range, $matches)) return null;
if ($matches[1] === 'append') {
return [self::RANGE_APPEND];
} elseif (strlen($matches[2]) > 0) {
return [self::RANGE_START, $matches[2], $matches[3] ?: null];
} else {
return [self::RANGE_END, $matches[4]];
}
}
}
| anaqreon/hubzilla | vendor/sabre/dav/lib/DAV/PartialUpdate/Plugin.php | PHP | mit | 6,501 |
/*
Ring.js
Copyright (c) 2013, Nicolas Vanhoren
Released under the MIT license
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function() {
/* jshint es3: true, proto: true */
"use strict";
if (typeof(exports) !== "undefined") { // nodejs
var underscore = require("underscore");
underscore.extend(exports, declare(underscore));
} else if (typeof(define) !== "undefined") { // amd
define(["underscore"], declare);
} else { // define global variable
window.ring = declare(_);
}
function declare(_) {
var ring = {};
function RingObject() {}
/**
ring.Object
The base class of all other classes. It doesn't have much uses except
testing testing if an object uses the Ring.js class system using
ring.instance(x, ring.Object)
*/
ring.Object = RingObject;
_.extend(ring.Object, {
__mro__: [ring.Object],
__properties__: {__ringConstructor__: function() {}},
__classId__: 1,
__parents__: [],
__classIndex__: {"1": ring.Object}
});
_.extend(ring.Object.prototype, {
__ringConstructor__: ring.Object.__properties__.__ringConstructor__
});
// utility function to have Object.create on all browsers
var objectCreate = function(o) {
function CreatedObject(){}
CreatedObject.prototype = o;
var tmp = new CreatedObject();
tmp.__proto__ = o;
return tmp;
};
ring.__objectCreate = objectCreate;
var classCounter = 3;
var fnTest = /xyz/.test(function(){xyz();}) ? /\$super\b/ : /.*/;
/**
ring.create([parents,] properties)
Creates a new class and returns it.
properties is a dictionary of the methods and attributes that should
be added to the new class' prototype.
parents is a list of the classes this new class should extend. If not
specified or an empty list is specified this class will inherit from one
class: ring.Object.
*/
ring.create = function() {
// arguments parsing
var args = _.toArray(arguments);
args.reverse();
var props = args[0];
var parents = args.length >= 2 ? args[1] : [];
if (! (parents instanceof Array))
parents = [parents];
_.each(parents, function(el) {
toRingClass(el);
});
if (parents.length === 0)
parents = [ring.Object];
// constructor handling
var cons = props.constructor !== Object ? props.constructor : undefined;
props = _.clone(props);
delete props.constructor;
if (cons)
props.__ringConstructor__ = cons;
else { //retro compatibility
cons = props.init;
delete props.init;
if (cons)
props.__ringConstructor__ = cons;
}
// create real class
var claz = function Instance() {
this.$super = null;
this.__ringConstructor__.apply(this, arguments);
};
claz.__properties__ = props;
// mro creation
var toMerge = _.pluck(parents, "__mro__");
toMerge = toMerge.concat([parents]);
var __mro__ = [claz].concat(mergeMro(toMerge));
//generate prototype
var prototype = Object.prototype;
_.each(_.clone(__mro__).reverse(), function(claz) {
var current = objectCreate(prototype);
_.extend(current, claz.__properties__);
_.each(_.keys(current), function(key) {
var p = current[key];
if (typeof p !== "function" || ! fnTest.test(p) || p.__classId__ ||
(key !== "__ringConstructor__" && claz.__ringConvertedObject__))
return;
current[key] = (function(name, fct, supProto) {
return function() {
var tmp = this.$super;
this.$super = supProto[name];
try {
return fct.apply(this, arguments);
} finally {
this.$super = tmp;
}
};
})(key, p, prototype);
});
current.constructor = claz;
prototype = current;
});
// remaining operations
var id = classCounter++;
claz.__mro__ = __mro__;
claz.__parents__ = parents;
claz.prototype = prototype;
claz.__classId__ = id;
// construct classes index
claz.__classIndex__ = {};
_.each(claz.__mro__, function(c) {
claz.__classIndex__[c.__classId__] = c;
});
// class init
if (claz.prototype.classInit) {
claz.__classInit__ = claz.prototype.classInit;
delete claz.prototype.classInit;
}
_.each(_.chain(claz.__mro__).clone().reverse().value(), function(c) {
if (c.__classInit__) {
var ret = c.__classInit__(claz.prototype);
if (ret !== undefined)
claz.prototype = ret;
}
});
return claz;
};
var mergeMro = function(toMerge) {
/* jshint loopfunc:true */
// C3 merge() implementation
var __mro__ = [];
var current = _.clone(toMerge);
while (true) {
var found = false;
for (var i=0; i < current.length; i++) {
if (current[i].length === 0)
continue;
var currentClass = current[i][0];
var isInTail = _.find(current, function(lst) {
return _.contains(_.rest(lst), currentClass);
});
if (! isInTail) {
found = true;
__mro__.push(currentClass);
current = _.map(current, function(lst) {
if (_.head(lst) === currentClass)
return _.rest(lst);
else
return lst;
});
break;
}
}
if (found)
continue;
if (_.all(current, function(i) { return i.length === 0; }))
return __mro__;
throw new ring.ValueError("Cannot create a consistent method resolution order (MRO)");
}
};
/**
Convert an existing class to be used with the ring.js class system.
*/
var toRingClass = function(claz) {
if (claz.__classId__)
return;
var proto = ! Object.getOwnPropertyNames ? claz.prototype : (function() {
var keys = {};
(function crawl(p) {
if (p === Object.prototype)
return;
_.extend(keys, _.chain(Object.getOwnPropertyNames(p))
.map(function(el) {return [el, true];})
.object().value());
crawl(Object.getPrototypeOf(p));
})(claz.prototype);
return _.object(_.map(_.keys(keys), function(k) {return [k, claz.prototype[k]];}));
})();
proto = _.chain(proto).map(function(v, k) { return [k, v]; })
.filter(function(el) {return el[0] !== "constructor" && el[0] !== "__proto__";})
.object().value();
var id = classCounter++;
_.extend(claz, {
__mro__: [claz, ring.Object],
__properties__: _.extend({}, proto, {
__ringConstructor__: function() {
this.$super.apply(this, arguments);
var tmp = this.$super;
this.$super = null;
try {
claz.apply(this, arguments);
} finally {
this.$super = tmp;
}
}
}),
__classId__: id,
__parents__: [ring.Object],
__classIndex__: {"1": ring.Object},
__ringConvertedObject__: true
});
claz.__classIndex__[id] = claz;
};
/**
ring.instance(obj, type)
Returns true if obj is an instance of type or an instance of a sub-class of type.
It is necessary to use this method instead of instanceof when using the Ring.js class
system because instanceof will not be able to detect sub-classes.
If used with obj or type that do not use the Ring.js class system this method will
use instanceof instead. So it should be safe to replace all usages of instanceof
by ring.instance() in any program, whether or not it uses Ring.js.
Additionaly this method allows to test the type of simple JavaScript types like strings.
To do so, pass a string instead of a type as second argument. Examples:
ring.instance("", "string") // returns true
ring.instance(function() {}, "function") // returns true
ring.instance({}, "object") // returns true
ring.instance(1, "number") // returns true
*/
ring.instance = function(obj, type) {
if (obj !== null && typeof(obj) === "object" && obj.constructor && obj.constructor.__classIndex__ &&
typeof(type) === "function" && typeof(type.__classId__) === "number") {
return obj.constructor.__classIndex__[type.__classId__] !== undefined;
}
if (typeof(type) === "string")
return typeof(obj) === type;
return obj instanceof type;
};
/**
A class to easily create new classes representing exceptions. This class is special
because it is a sub-class of the standard Error class of JavaScript. Examples:
ring.instance(e, Error)
e instanceof Error
This two expressions will always be true if e is an instance of ring.Error or any
sub-class of ring.Error.
*/
ring.Error = ring.create({
/**
The name attribute is used in the default implementation of the toString() method
of the standard JavaScript Error class. According to the standard, all sub-classes
of Error should define a new name.
*/
name: "ring.Error",
/**
A default message to use in instances of this class if there is no arguments given
to the constructor.
*/
defaultMessage: "",
/**
Constructor arguments:
message: The message to put in the instance. If there is no message specified, the
message will be this.defaultMessage.
*/
constructor: function(message) {
this.message = message || this.defaultMessage;
},
classInit: function(prototype) {
// some black magic to reconstitute a complete prototype chain
// with Error at the end
var protos = [];
var gather = function(proto) {
if (! proto)
return;
protos.push(proto);
gather(proto.__proto__);
};
gather(prototype);
var current = new Error();
_.each(_.clone(protos).reverse(), function(proto) {
var tmp = objectCreate(current);
// using _.each to avoid traversing prototypes
_.each(proto, function(v, k) {
if (k !== "__proto__")
tmp[k] = v;
});
current = tmp;
});
return current;
}
});
/**
A type of exception to inform that a method received an argument with an incorrect value.
*/
ring.ValueError = ring.create([ring.Error], {
name: "ring.ValueError"
});
/**
This method allows to find the super of a method when that method has been re-defined
in a child class.
Contrary to this.$super(), this function allows to find a super method in another method
than the re-defining one. Example:
var A = ring.create({
fctA: function() {...};
});
var B = ring.create([A], {
fctA: function() {...};
fctB: function() {
ring.getSuper(B, this, "fctA")(); // here we call the original fctA() method
// as it was defined in the A class
};
});
This method is much slower than this.$super(), so this.$super() should always be
preferred when it is possible to use it.
Arguments:
* currentClass: The current class. It is necessary to specify it for this function
to work properly.
* obj: The current object (this in most cases).
* attributeName: The name of the desired attribute as it appeared in the base class.
Returns the attribute as it was defined in the base class. If that attribute is a function,
it will be binded to obj.
*/
ring.getSuper = function(currentClass, obj, attributeName) {
var pos;
var __mro__ = obj.constructor.__mro__;
for (var i = 0; i < __mro__.length; i++) {
if (__mro__[i] === currentClass) {
pos = i;
break;
}
}
if (pos === undefined)
throw new ring.ValueError("Class not found in instance's method resolution order.");
var find = function(proto, counter) {
if (counter === 0)
return proto;
return find(proto.__proto__, counter - 1);
};
var proto = find(obj.constructor.prototype, pos + 1);
var att;
if (attributeName !== "constructor" && attributeName !== "init") // retro compatibility
att = proto[attributeName];
else
att = proto.__ringConstructor__;
if (ring.instance(att, "function"))
return _.bind(att, obj);
else
return att;
};
return ring;
}
})();
| holtkamp/cdnjs | ajax/libs/ring.js/2.0.2/ring.js | JavaScript | mit | 15,046 |
// Chinese (Taiwan) (zh_TW)
plupload.addI18n({"Stop Upload":"停止上傳","Upload URL might be wrong or doesn't exist.":"檔案URL可能有誤或者不存在。","tb":"tb","Size":"大小","Close":"關閉","You must specify either browse_button or drop_element.":"您必須指定 browse_button 或 drop_element。","Init error.":"初始化錯誤。","Add files to the upload queue and click the start button.":"將檔案加入上傳序列,然後點選”開始上傳“按鈕。","List":"清單","Filename":"檔案名稱","%s specified, but cannot be found.":"找不到已選擇的 %s。","Image format either wrong or not supported.":"圖片格式錯誤或者不支援。","Status":"狀態","HTTP Error.":"HTTP 錯誤。","Start Upload":"開始上傳","Error: File too large:":"錯誤: 檔案大小太大:","kb":"kb","Duplicate file error.":"錯誤:檔案重複。","File size error.":"錯誤:檔案大小超過限制。","N/A":"N/A","gb":"gb","Error: Invalid file extension:":"錯誤:不接受的檔案格式:","Select files":"選擇檔案","%s already present in the queue.":"%s 已經存在目前的檔案序列。","Resoultion out of boundaries! <b>%s</b> runtime supports images only up to %wx%hpx.":"圖片解析度超出範圍! <b>%s</b> 最高只支援到 %wx%hpx。","File: %s":"檔案: %s","b":"b","Uploaded %d/%d files":"已上傳 %d/%d 個文件","Upload element accepts only %d file(s) at a time. Extra files were stripped.":"每次只能上傳 %d 個檔案,超過限制數量的檔案將被忽略。","%d files queued":"%d 個檔案加入到序列","File: %s, size: %d, max file size: %d":"檔案: %s, 大小: %d, 檔案大小上限: %d","Thumbnails":"縮圖","Drag files here.":"把檔案拖曳到這裡。","Runtime ran out of available memory.":"執行時耗盡了所有可用的記憶體。","File count error.":"檔案數量錯誤。","File extension error.":"檔案副檔名錯誤。","mb":"mb","Add Files":"增加檔案"}); | BenjaminVanRyseghem/cdnjs | ajax/libs/plupload/2.3.1/i18n/zh_TW.js | JavaScript | mit | 1,957 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 2.0.3
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* SQLSRV Utility Class
*
* @category Database
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
class CI_DB_sqlsrv_utility extends CI_DB_utility {
/**
* List databases statement
*
* @var string
*/
protected $_list_databases = 'EXEC sp_helpdb'; // Can also be: EXEC sp_databases
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $_optimize_table = 'ALTER INDEX all ON %s REORGANIZE';
// --------------------------------------------------------------------
/**
* Export
*
* @param array $params Preferences
* @return bool
*/
protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsupported_feature');
}
}
| wanghaokk/CI_HealthCare | system/database/drivers/sqlsrv/sqlsrv_utility.php | PHP | mit | 2,488 |
/*!
* inferno-create-class v1.0.0-beta30
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno-component')) :
typeof define === 'function' && define.amd ? define(['inferno-component'], factory) :
(global.Inferno = global.Inferno || {}, global.Inferno.createClass = factory(global.Inferno.Component));
}(this, (function (Component) { 'use strict';
Component = 'default' in Component ? Component['default'] : Component;
var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.';
// this is MUCH faster than .constructor === Array and instanceof Array
// in Node 7 and the later versions of V8, slower in older versions though
function isNullOrUndef(obj) {
return isUndefined(obj) || isNull(obj);
}
function isFunction(obj) {
return typeof obj === 'function';
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
// don't autobind these methods since they already have guaranteed context.
var AUTOBIND_BLACKLIST = {
constructor: 1,
render: 1,
shouldComponentUpdate: 1,
componentWillRecieveProps: 1,
componentWillUpdate: 1,
componentDidUpdate: 1,
componentWillMount: 1,
componentDidMount: 1,
componentWillUnmount: 1,
componentDidUnmount: 1
};
function extend(base, props, all) {
for (var key in props) {
if (all === true || !isNullOrUndef(props[key])) {
base[key] = props[key];
}
}
return base;
}
function bindAll(ctx) {
for (var i in ctx) {
var v = ctx[i];
if (typeof v === 'function' && !v.__bound && !AUTOBIND_BLACKLIST[i]) {
(ctx[i] = v.bind(ctx)).__bound = true;
}
}
}
function collateMixins(mixins, keyed) {
if ( keyed === void 0 ) keyed = {};
for (var i = 0; i < mixins.length; i++) {
var mixin = mixins[i];
// Surprise: Mixins can have mixins
if (mixin.mixins) {
// Recursively collate sub-mixins
collateMixins(mixin.mixins, keyed);
}
for (var key in mixin) {
if (mixin.hasOwnProperty(key) && typeof mixin[key] === 'function') {
(keyed[key] || (keyed[key] = [])).push(mixin[key]);
}
}
}
return keyed;
}
function applyMixin(key, inst, mixin) {
var original = inst[key];
inst[key] = function () {
var arguments$1 = arguments;
var ret;
for (var i = 0; i < mixin.length; i++) {
var method = mixin[i];
var _ret = method.apply(inst, arguments$1);
if (!isUndefined(_ret)) {
ret = _ret;
}
}
if (original) {
var _ret$1 = original.call(inst);
if (!isUndefined(_ret$1)) {
ret = _ret$1;
}
}
return ret;
};
}
function applyMixins(inst, mixins) {
for (var key in mixins) {
if (mixins.hasOwnProperty(key)) {
var mixin = mixins[key];
if (isFunction(mixin[0])) {
applyMixin(key, inst, mixin);
}
else {
inst[key] = mixin;
}
}
}
}
function createClass$1(obj) {
var Cl = (function (Component$$1) {
function Cl(props) {
Component$$1.call(this, props);
this.isMounted = function () { return !this._unmounted; };
extend(this, obj);
if (Cl.mixins) {
applyMixins(this, Cl.mixins);
}
bindAll(this);
if (obj.getInitialState) {
this.state = obj.getInitialState.call(this);
}
}
if ( Component$$1 ) Cl.__proto__ = Component$$1;
Cl.prototype = Object.create( Component$$1 && Component$$1.prototype );
Cl.prototype.constructor = Cl;
return Cl;
}(Component));
Cl.displayName = obj.displayName || 'Component';
Cl.propTypes = obj.propTypes;
Cl.defaultProps = obj.getDefaultProps ? obj.getDefaultProps() : undefined;
Cl.mixins = obj.mixins && collateMixins(obj.mixins);
if (obj.statics) {
extend(Cl, obj.statics);
}
return Cl;
}
return createClass$1;
})));
| dc-js/cdnjs | ajax/libs/inferno/1.0.0-beta30/inferno-create-class.js | JavaScript | mit | 4,390 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Translation\Tests\Formatter;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\Formatter\MessageFormatter;
class MessageFormatterTest extends TestCase
{
/**
* @dataProvider getTransMessages
*/
public function testFormat($expected, $message, $parameters = [])
{
$this->assertEquals($expected, $this->getMessageFormatter()->format($message, 'en', $parameters));
}
public function getTransMessages()
{
return [
[
'There is one apple',
'There is one apple',
],
[
'There are 5 apples',
'There are %count% apples',
['%count%' => 5],
],
[
'There are 5 apples',
'There are {{count}} apples',
['{{count}}' => 5],
],
];
}
private function getMessageFormatter()
{
return new MessageFormatter();
}
}
| garak/symfony | src/Symfony/Component/Translation/Tests/Formatter/MessageFormatterTest.php | PHP | mit | 1,256 |
/**
* @ngdoc directive
* @name kml-layer
* @param Attr2MapOptions {service} convert html attribute to Gogole map api options
* @description
* renders Kml layer on a map
* Requires: map directive
* Restrict To: Element
*
* @attr {Url} url url of the kml layer
* @attr {KmlLayerOptions} KmlLayerOptions
* (https://developers.google.com/maps/documentation/javascript/reference#KmlLayerOptions)
* @attr {String} <KmlLayerEvent> Any KmlLayer events,
* https://developers.google.com/maps/documentation/javascript/reference
* @example
* Usage:
* <map MAP_ATTRIBUTES>
* <kml-layer ANY_KML_LAYER ANY_KML_LAYER_EVENTS"></kml-layer>
* </map>
*
* Example:
*
* <map zoom="11" center="[41.875696,-87.624207]">
* <kml-layer url="https://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml" >
* </kml-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('kmlLayer', [
'Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
var getKmlLayer = function(options, events) {
var kmlLayer = new google.maps.KmlLayer(options);
for (var eventName in events) {
google.maps.event.addListener(kmlLayer, eventName, events[eventName]);
}
return kmlLayer;
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
console.log('kml-layer options', options, 'events', events);
var kmlLayer = getKmlLayer(options, events);
mapController.addObject('kmlLayers', kmlLayer);
mapController.observeAttrSetObj(orgAttrs, attrs, kmlLayer); //observers
element.bind('$destroy', function() {
mapController.deleteObject('kmlLayers', kmlLayer);
});
}
}; // return
}]);
})();
| monsterxxx/muine | bower_components/ngmap/directives/kml-layer.js | JavaScript | mit | 2,122 |
.mep-container{position:relative;background:#000;font-family:Helvetica,Arial;}.mep-container-fullscreen{position:fixed;left:0;top:0;right:0;bottom:0;overflow:hidden;}.mep-container-fullscreen .mep-mediaelement,.mep-container-fullscreen video{width:100%;height:100%;}.mep-mediaelement{position:absolute;top:0;left:0;}.mep-poster{position:absolute;top:0;left:0;}.mep-overlay{position:absolute;top:0;left:0;display:table;}.mep-overlay-message{display:table-cell;text-align:center;vertical-align:middle;color:#fff;text-shadow:#000 1px 1px 1px;font-size:24px;font-weight:bold;}.mep-container .mep-controls{position:absolute;background:none;list-style-type:none;margin:0;padding:0;bottom:0;left:0;background:url(background.png);background:rgba(0,0,0,0.7);height:30px;width:100%;}.mep-container .mep-controls div{list-style-type:none;background-image:none;display:inline-block;float:left;margin:5px 5px 5px 0;padding:0;width:20px;height:20px;font-size:11px;line-height:11px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;font-family:Helvetica,Arial;}.mep-container .mep-controls div:first-child{margin-left:5px;}.mep-container .mep-controls .mep-time{color:#fff;display:block;width:80px;height:17px;padding:3px 0 0 0;overflow:hidden;text-align:center;}.mep-container .mep-controls .mep-time span{font-size:11px;color:#fff;line-height:1em;display:inline-block;}.mep-controls .mep-playpause-button span,.mep-controls .mep-volume-button span,.mep-controls .mep-fullscreen-button span{cursor:pointer;display:block;font-size:0;line-height:0;text-decoration:none;margin:2px;height:16px;width:16px;background:transparent url(controls.png) 0 0 no-repeat;}.mep-controls .mep-play span{background-position:0 0;}.mep-controls .mep-pause span{background-position:0 -16px;}.mep-controls .mep-time-rail{width:200px;}.mep-controls .mep-time-rail span{display:block;position:absolute;width:180px;height:10px;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px;cursor:pointer;}.mep-controls .mep-time-rail .mep-time-total{margin:5px;background:#333;background:rgba(0,0,0,0.8);}.mep-controls .mep-time-rail .mep-time-loaded{background:#3caac8;background:rgba(60,170,200,0.8);}.mep-controls .mep-time-rail .mep-time-current{background:#fff;background:rgba(255,255,255,0.8);}.mep-controls .mep-time-rail .mep-time-handle{display:block;position:absolute;margin:0;width:10px;background:#fff;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;cursor:pointer;display:none;}.mep-controls .mep-fullscreen-button span{background-position:-32px 0;}.mep-controls .mep-unfullscreen span{background-position:-32px -16px;}.mep-controls .mep-mute span{background-position:-16px -16px;}.mep-controls .mep-unmute span{background-position:-16px 0;}.mep-controls .mep-volume-button .mep-volume-slider{display:none;height:115px;width:20px;background:#333;background:rgba(0,0,0,0.7);-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;top:-110px;position:absolute;margin:0;}.mep-controls .mep-volume-button:hover{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;}.mep-controls .mep-volume-button:hover .mep-volume-slider{display:block;}.mep-controls .mep-volume-button .mep-volume-slider .mep-volume-rail{position:absolute;left:9px;top:8px;width:2px;height:100px;background:#ddd;background:rgba(255,255,255,0.8);margin:0;}.mep-controls .mep-volume-button .mep-volume-slider .mep-volume-rail .mep-volume-handle{position:absolute;left:-7px;top:-3px;width:16px;height:6px;background:#ddd;background:rgba(255,255,255,0.9);cursor:N-resize;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;margin:0;}.mep-clear{clear:both;} | khasinski/cdnjs | ajax/libs/mediaelement/1.1/mediaelementplayer.min.css | CSS | mit | 3,690 |
//>>built
define(
"dojo/nls/es/colors", //begin v1.x content
({
// local representation of all CSS3 named colors, companion to dojo.colors. To be used where descriptive information
// is required for each color, such as a palette widget, and not for specifying color programatically.
//Note: due to the SVG 1.0 spec additions, some of these are alternate spellings for the same color e.g. gray vs. gray.
//TODO: should we be using unique rgb values as keys instead and avoid these duplicates, or rely on the caller to do the reverse mapping?
aliceblue: "blanco azulado",
antiquewhite: "blanco antiguo",
aqua: "aguamarina",
aquamarine: "aguamarina 2",
azure: "blanco cielo",
beige: "beige",
bisque: "miel",
black: "negro",
blanchedalmond: "almendra pálido",
blue: "azul",
blueviolet: "azul violáceo",
brown: "marrón",
burlywood: "madera",
cadetblue: "azul cadete",
chartreuse: "verde pálido 2",
chocolate: "chocolate",
coral: "coral",
cornflowerblue: "azul aciano",
cornsilk: "crudo",
crimson: "carmesí",
cyan: "cian",
darkblue: "azul oscuro",
darkcyan: "cian oscuro",
darkgoldenrod: "ocre oscuro",
darkgray: "gris oscuro",
darkgreen: "verde oscuro",
darkgrey: "gris oscuro", // same as darkgray
darkkhaki: "caqui oscuro",
darkmagenta: "magenta oscuro",
darkolivegreen: "verde oliva oscuro",
darkorange: "naranja oscuro",
darkorchid: "orquídea oscuro",
darkred: "rojo oscuro",
darksalmon: "salmón oscuro",
darkseagreen: "verde mar oscuro",
darkslateblue: "azul pizarra oscuro",
darkslategray: "gris pizarra oscuro",
darkslategrey: "gris pizarra oscuro", // same as darkslategray
darkturquoise: "turquesa oscuro",
darkviolet: "violeta oscuro",
deeppink: "rosa fuerte",
deepskyblue: "azul cielo fuerte",
dimgray: "gris marengo",
dimgrey: "gris marengo", // same as dimgray
dodgerblue: "azul fuerte",
firebrick: "teja",
floralwhite: "blanco manteca",
forestgreen: "verde pino",
fuchsia: "fucsia",
gainsboro: "azul gainsboro",
ghostwhite: "blanco ligero",
gold: "oro",
goldenrod: "ocre",
gray: "gris",
green: "verde",
greenyellow: "amarillo verdoso",
grey: "gris", // same as gray
honeydew: "flor de rocío",
hotpink: "rosa oscuro",
indianred: "rojo teja",
indigo: "añil",
ivory: "marfil",
khaki: "caqui",
lavender: "lavanda",
lavenderblush: "lavanda rosácea",
lawngreen: "verde césped",
lemonchiffon: "amarillo pastel",
lightblue: "azul claro",
lightcoral: "coral claro",
lightcyan: "cian claro",
lightgoldenrodyellow: "ocre claro",
lightgray: "gris claro",
lightgreen: "verde claro",
lightgrey: "gris claro", // same as lightgray
lightpink: "rosa claro",
lightsalmon: "salmón claro",
lightseagreen: "verde mar claro",
lightskyblue: "azul cielo claro",
lightslategray: "gris pizarra claro",
lightslategrey: "gris pizarra claro", // same as lightslategray
lightsteelblue: "azul acero claro",
lightyellow: "amarillo claro",
lime: "lima",
limegreen: "lima limón",
linen: "blanco arena",
magenta: "magenta",
maroon: "granate",
mediumaquamarine: "aguamarina medio",
mediumblue: "azul medio",
mediumorchid: "orquídea medio",
mediumpurple: "púrpura medio",
mediumseagreen: "verde mar medio",
mediumslateblue: "azul pizarra medio",
mediumspringgreen: "verde primavera medio",
mediumturquoise: "turquesa medio",
mediumvioletred: "rojo violáceo medio",
midnightblue: "azul medianoche",
mintcream: "crema menta",
mistyrose: "rosa difuminado",
moccasin: "arena",
navajowhite: "blanco navajo",
navy: "azul marino",
oldlace: "encaje antiguo",
olive: "verde oliva",
olivedrab: "verde oliva pardusco",
orange: "naranja",
orangered: "rojo anaranjado",
orchid: "orquídea",
palegoldenrod: "ocre pálido",
palegreen: "verde pálido",
paleturquoise: "turquesa pálido",
palevioletred: "rojo violáceo pálido",
papayawhip: "papaya claro",
peachpuff: "melocotón",
peru: "perú",
pink: "rosa",
plum: "ciruela",
powderblue: "azul suave",
purple: "púrpura",
red: "rojo",
rosybrown: "marrón rosáceo",
royalblue: "azul real",
saddlebrown: "cuero",
salmon: "salmón",
sandybrown: "marrón arcilla",
seagreen: "verde mar",
seashell: "blanco marfil",
sienna: "siena",
silver: "plateado",
skyblue: "azul cielo",
slateblue: "azul pizarra",
slategray: "gris pizarra",
slategrey: "gris pizarra", // same as slategray
snow: "nieve",
springgreen: "verde fuerte",
steelblue: "azul acero",
tan: "canela",
teal: "verde azulado",
thistle: "cardo",
tomato: "tomate",
transparent: "transparente",
turquoise: "turquesa",
violet: "violeta",
wheat: "trigo",
white: "blanco",
whitesmoke: "blanco ahumado",
yellow: "amarillo",
yellowgreen: "verde amarillento"
})
//end v1.x content
);
| ppoffice/cdnjs | ajax/libs/dojo/1.7.2/nls/es/colors.js | JavaScript | mit | 4,556 |
/*!
* MediaElement.js
* HTML5 <video> and <audio> shim and player
* http://mediaelementjs.com/
*
* Creates a JavaScript object that mimics HTML5 MediaElement API
* for browsers that don't understand HTML5 or can't play the provided codec
* Can play MP4 (H.264), Ogg, WebM, FLV, WMV, WMA, ACC, and MP3
*
* Copyright 2010-2012, John Dyer (http://j.hn)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
// Namespace
var mejs = mejs || {};
// version number
mejs.version = '2.9.0';
// player number (for missing, same id attr)
mejs.meIndex = 0;
// media types accepted by plugins
mejs.plugins = {
silverlight: [
{version: [3,0], types: ['video/mp4','video/m4v','video/mov','video/wmv','audio/wma','audio/m4a','audio/mp3','audio/wav','audio/mpeg']}
],
flash: [
{version: [9,0,124], types: ['video/mp4','video/m4v','video/mov','video/flv','video/x-flv','audio/flv','audio/x-flv','audio/mp3','audio/m4a','audio/mpeg', 'video/youtube', 'video/x-youtube']}
//,{version: [12,0], types: ['video/webm']} // for future reference (hopefully!)
],
youtube: [
{version: null, types: ['video/youtube', 'video/x-youtube']}
],
vimeo: [
{version: null, types: ['video/vimeo']}
]
};
/*
Utility methods
*/
mejs.Utility = {
encodeUrl: function(url) {
return encodeURIComponent(url); //.replace(/\?/gi,'%3F').replace(/=/gi,'%3D').replace(/&/gi,'%26');
},
escapeHTML: function(s) {
return s.toString().split('&').join('&').split('<').join('<').split('"').join('"');
},
absolutizeUrl: function(url) {
var el = document.createElement('div');
el.innerHTML = '<a href="' + this.escapeHTML(url) + '">x</a>';
return el.firstChild.href;
},
getScriptPath: function(scriptNames) {
var
i = 0,
j,
path = '',
name = '',
script,
scripts = document.getElementsByTagName('script'),
il = scripts.length,
jl = scriptNames.length;
for (; i < il; i++) {
script = scripts[i].src;
for (j = 0; j < jl; j++) {
name = scriptNames[j];
if (script.indexOf(name) > -1) {
path = script.substring(0, script.indexOf(name));
break;
}
}
if (path !== '') {
break;
}
}
return path;
},
secondsToTimeCode: function(time, forceHours, showFrameCount, fps) {
//add framecount
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var hours = Math.floor(time / 3600) % 24,
minutes = Math.floor(time / 60) % 60,
seconds = Math.floor(time % 60),
frames = Math.floor(((time % 1)*fps).toFixed(3)),
result =
( (forceHours || hours > 0) ? (hours < 10 ? '0' + hours : hours) + ':' : '')
+ (minutes < 10 ? '0' + minutes : minutes) + ':'
+ (seconds < 10 ? '0' + seconds : seconds)
+ ((showFrameCount) ? ':' + (frames < 10 ? '0' + frames : frames) : '');
return result;
},
timeCodeToSeconds: function(hh_mm_ss_ff, forceHours, showFrameCount, fps){
if (typeof showFrameCount == 'undefined') {
showFrameCount=false;
} else if(typeof fps == 'undefined') {
fps = 25;
}
var tc_array = hh_mm_ss_ff.split(":"),
tc_hh = parseInt(tc_array[0], 10),
tc_mm = parseInt(tc_array[1], 10),
tc_ss = parseInt(tc_array[2], 10),
tc_ff = 0,
tc_in_seconds = 0;
if (showFrameCount) {
tc_ff = parseInt(tc_array[3])/fps;
}
tc_in_seconds = ( tc_hh * 3600 ) + ( tc_mm * 60 ) + tc_ss + tc_ff;
return tc_in_seconds;
},
/* borrowed from SWFObject: http://code.google.com/p/swfobject/source/browse/trunk/swfobject/src/swfobject.js#474 */
removeSwf: function(id) {
var obj = document.getElementById(id);
if (obj && obj.nodeName == "OBJECT") {
if (mejs.MediaFeatures.isIE) {
obj.style.display = "none";
(function(){
if (obj.readyState == 4) {
mejs.Utility.removeObjectInIE(id);
} else {
setTimeout(arguments.callee, 10);
}
})();
} else {
obj.parentNode.removeChild(obj);
}
}
},
removeObjectInIE: function(id) {
var obj = document.getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null;
}
}
obj.parentNode.removeChild(obj);
}
}
};
// Core detector, plugins are added below
mejs.PluginDetector = {
// main public function to test a plug version number PluginDetector.hasPluginVersion('flash',[9,0,125]);
hasPluginVersion: function(plugin, v) {
var pv = this.plugins[plugin];
v[1] = v[1] || 0;
v[2] = v[2] || 0;
return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
},
// cached values
nav: window.navigator,
ua: window.navigator.userAgent.toLowerCase(),
// stored version numbers
plugins: [],
// runs detectPlugin() and stores the version number
addPlugin: function(p, pluginName, mimeType, activeX, axDetect) {
this.plugins[p] = this.detectPlugin(pluginName, mimeType, activeX, axDetect);
},
// get the version number from the mimetype (all but IE) or ActiveX (IE)
detectPlugin: function(pluginName, mimeType, activeX, axDetect) {
var version = [0,0,0],
description,
i,
ax;
// Firefox, Webkit, Opera
if (typeof(this.nav.plugins) != 'undefined' && typeof this.nav.plugins[pluginName] == 'object') {
description = this.nav.plugins[pluginName].description;
if (description && !(typeof this.nav.mimeTypes != 'undefined' && this.nav.mimeTypes[mimeType] && !this.nav.mimeTypes[mimeType].enabledPlugin)) {
version = description.replace(pluginName, '').replace(/^\s+/,'').replace(/\sr/gi,'.').split('.');
for (i=0; i<version.length; i++) {
version[i] = parseInt(version[i].match(/\d+/), 10);
}
}
// Internet Explorer / ActiveX
} else if (typeof(window.ActiveXObject) != 'undefined') {
try {
ax = new ActiveXObject(activeX);
if (ax) {
version = axDetect(ax);
}
}
catch (e) { }
}
return version;
}
};
// Add Flash detection
mejs.PluginDetector.addPlugin('flash','Shockwave Flash','application/x-shockwave-flash','ShockwaveFlash.ShockwaveFlash', function(ax) {
// adapted from SWFObject
var version = [],
d = ax.GetVariable("$version");
if (d) {
d = d.split(" ")[1].split(",");
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
// Add Silverlight detection
mejs.PluginDetector.addPlugin('silverlight','Silverlight Plug-In','application/x-silverlight-2','AgControl.AgControl', function (ax) {
// Silverlight cannot report its version number to IE
// but it does have a isVersionSupported function, so we have to loop through it to get a version number.
// adapted from http://www.silverlightversion.com/
var v = [0,0,0,0],
loopMatch = function(ax, v, i, n) {
while(ax.isVersionSupported(v[0]+ "."+ v[1] + "." + v[2] + "." + v[3])){
v[i]+=n;
}
v[i] -= n;
};
loopMatch(ax, v, 0, 1);
loopMatch(ax, v, 1, 1);
loopMatch(ax, v, 2, 10000); // the third place in the version number is usually 5 digits (4.0.xxxxx)
loopMatch(ax, v, 2, 1000);
loopMatch(ax, v, 2, 100);
loopMatch(ax, v, 2, 10);
loopMatch(ax, v, 2, 1);
loopMatch(ax, v, 3, 1);
return v;
});
// add adobe acrobat
/*
PluginDetector.addPlugin('acrobat','Adobe Acrobat','application/pdf','AcroPDF.PDF', function (ax) {
var version = [],
d = ax.GetVersions().split(',')[0].split('=')[1].split('.');
if (d) {
version = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
}
return version;
});
*/
// necessary detection (fixes for <IE9)
mejs.MediaFeatures = {
init: function() {
var
t = this,
d = document,
nav = mejs.PluginDetector.nav,
ua = mejs.PluginDetector.ua.toLowerCase(),
i,
v,
html5Elements = ['source','track','audio','video'];
// detect browsers (only the ones that have some kind of quirk we need to work around)
t.isiPad = (ua.match(/ipad/i) !== null);
t.isiPhone = (ua.match(/iphone/i) !== null);
t.isiOS = t.isiPhone || t.isiPad;
t.isAndroid = (ua.match(/android/i) !== null);
t.isBustedAndroid = (ua.match(/android 2\.[12]/) !== null);
t.isIE = (nav.appName.toLowerCase().indexOf("microsoft") != -1);
t.isChrome = (ua.match(/chrome/gi) !== null);
t.isFirefox = (ua.match(/firefox/gi) !== null);
t.isWebkit = (ua.match(/webkit/gi) !== null);
t.isGecko = (ua.match(/gecko/gi) !== null) && !t.isWebkit;
t.isOpera = (ua.match(/opera/gi) !== null);
t.hasTouch = ('ontouchstart' in window);
// create HTML5 media elements for IE before 9, get a <video> element for fullscreen detection
for (i=0; i<html5Elements.length; i++) {
v = document.createElement(html5Elements[i]);
}
t.supportsMediaTag = (typeof v.canPlayType !== 'undefined' || t.isBustedAndroid);
// detect native JavaScript fullscreen (Safari/Firefox only, Chrome still fails)
// iOS
t.hasSemiNativeFullScreen = (typeof v.webkitEnterFullscreen !== 'undefined');
// Webkit/firefox
t.hasWebkitNativeFullScreen = (typeof v.webkitRequestFullScreen !== 'undefined');
t.hasMozNativeFullScreen = (typeof v.mozRequestFullScreen !== 'undefined');
t.hasTrueNativeFullScreen = (t.hasWebkitNativeFullScreen || t.hasMozNativeFullScreen);
t.nativeFullScreenEnabled = t.hasTrueNativeFullScreen;
if (t.hasMozNativeFullScreen) {
t.nativeFullScreenEnabled = v.mozFullScreenEnabled;
}
if (this.isChrome) {
t.hasSemiNativeFullScreen = false;
}
if (t.hasTrueNativeFullScreen) {
t.fullScreenEventName = (t.hasWebkitNativeFullScreen) ? 'webkitfullscreenchange' : 'mozfullscreenchange';
t.isFullScreen = function() {
if (v.mozRequestFullScreen) {
return d.mozFullScreen;
} else if (v.webkitRequestFullScreen) {
return d.webkitIsFullScreen;
}
}
t.requestFullScreen = function(el) {
if (t.hasWebkitNativeFullScreen) {
el.webkitRequestFullScreen();
} else if (t.hasMozNativeFullScreen) {
el.mozRequestFullScreen();
}
}
t.cancelFullScreen = function() {
if (t.hasWebkitNativeFullScreen) {
document.webkitCancelFullScreen();
} else if (t.hasMozNativeFullScreen) {
document.mozCancelFullScreen();
}
}
}
// OS X 10.5 can't do this even if it says it can :(
if (t.hasSemiNativeFullScreen && ua.match(/mac os x 10_5/i)) {
t.hasNativeFullScreen = false;
t.hasSemiNativeFullScreen = false;
}
}
};
mejs.MediaFeatures.init();
/*
extension methods to <video> or <audio> object to bring it into parity with PluginMediaElement (see below)
*/
mejs.HtmlMediaElement = {
pluginType: 'native',
isFullScreen: false,
setCurrentTime: function (time) {
this.currentTime = time;
},
setMuted: function (muted) {
this.muted = muted;
},
setVolume: function (volume) {
this.volume = volume;
},
// for parity with the plugin versions
stop: function () {
this.pause();
},
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
// Fix for IE9 which can't set .src when there are <source> elements. Awesome, right?
var
existingSources = this.getElementsByTagName('source');
while (existingSources.length > 0){
this.removeChild(existingSources[0]);
}
if (typeof url == 'string') {
this.src = url;
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.src = media.src;
}
}
}
},
setVideoSize: function (width, height) {
this.width = width;
this.height = height;
}
};
/*
Mimics the <video/audio> element by calling Flash's External Interface or Silverlights [ScriptableMember]
*/
mejs.PluginMediaElement = function (pluginid, pluginType, mediaUrl) {
this.id = pluginid;
this.pluginType = pluginType;
this.src = mediaUrl;
this.events = {};
};
// JavaScript values and ExternalInterface methods that match HTML5 video properties methods
// http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
mejs.PluginMediaElement.prototype = {
// special
pluginElement: null,
pluginType: '',
isFullScreen: false,
// not implemented :(
playbackRate: -1,
defaultPlaybackRate: -1,
seekable: [],
played: [],
// HTML5 read-only properties
paused: true,
ended: false,
seeking: false,
duration: 0,
error: null,
tagName: '',
// HTML5 get/set properties, but only set (updated by event handlers)
muted: false,
volume: 1,
currentTime: 0,
// HTML5 methods
play: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.playVideo();
} else {
this.pluginApi.playMedia();
}
this.paused = false;
}
},
load: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
} else {
this.pluginApi.loadMedia();
}
this.paused = false;
}
},
pause: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.pauseVideo();
} else {
this.pluginApi.pauseMedia();
}
this.paused = true;
}
},
stop: function () {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.stopVideo();
} else {
this.pluginApi.stopMedia();
}
this.paused = true;
}
},
canPlayType: function(type) {
var i,
j,
pluginInfo,
pluginVersions = mejs.plugins[this.pluginType];
for (i=0; i<pluginVersions.length; i++) {
pluginInfo = pluginVersions[i];
// test if user has the correct plugin version
if (mejs.PluginDetector.hasPluginVersion(this.pluginType, pluginInfo.version)) {
// test for plugin playback types
for (j=0; j<pluginInfo.types.length; j++) {
// find plugin that can play the type
if (type == pluginInfo.types[j]) {
return true;
}
}
}
}
return false;
},
positionFullscreenButton: function(x,y,visibleAndAbove) {
if (this.pluginApi != null && this.pluginApi.positionFullscreenButton) {
this.pluginApi.positionFullscreenButton(x,y,visibleAndAbove);
}
},
hideFullscreenButton: function() {
if (this.pluginApi != null && this.pluginApi.hideFullscreenButton) {
this.pluginApi.hideFullscreenButton();
}
},
// custom methods since not all JavaScript implementations support get/set
// This can be a url string
// or an array [{src:'file.mp4',type:'video/mp4'},{src:'file.webm',type:'video/webm'}]
setSrc: function (url) {
if (typeof url == 'string') {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(url));
this.src = mejs.Utility.absolutizeUrl(url);
} else {
var i, media;
for (i=0; i<url.length; i++) {
media = url[i];
if (this.canPlayType(media.type)) {
this.pluginApi.setSrc(mejs.Utility.absolutizeUrl(media.src));
this.src = mejs.Utility.absolutizeUrl(url);
}
}
}
},
setCurrentTime: function (time) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
this.pluginApi.seekTo(time);
} else {
this.pluginApi.setCurrentTime(time);
}
this.currentTime = time;
}
},
setVolume: function (volume) {
if (this.pluginApi != null) {
// same on YouTube and MEjs
if (this.pluginType == 'youtube') {
this.pluginApi.setVolume(volume * 100);
} else {
this.pluginApi.setVolume(volume);
}
this.volume = volume;
}
},
setMuted: function (muted) {
if (this.pluginApi != null) {
if (this.pluginType == 'youtube') {
if (muted) {
this.pluginApi.mute();
} else {
this.pluginApi.unMute();
}
this.muted = muted;
this.dispatchEvent('volumechange');
} else {
this.pluginApi.setMuted(muted);
}
this.muted = muted;
}
},
// additional non-HTML5 methods
setVideoSize: function (width, height) {
//if (this.pluginType == 'flash' || this.pluginType == 'silverlight') {
if ( this.pluginElement.style) {
this.pluginElement.style.width = width + 'px';
this.pluginElement.style.height = height + 'px';
}
if (this.pluginApi != null && this.pluginApi.setVideoSize) {
this.pluginApi.setVideoSize(width, height);
}
//}
},
setFullscreen: function (fullscreen) {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.pluginApi.setFullscreen(fullscreen);
}
},
enterFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(true);
}
},
exitFullScreen: function() {
if (this.pluginApi != null && this.pluginApi.setFullscreen) {
this.setFullscreen(false);
}
},
// start: fake events
addEventListener: function (eventName, callback, bubble) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(callback);
},
removeEventListener: function (eventName, callback) {
if (!eventName) { this.events = {}; return true; }
var callbacks = this.events[eventName];
if (!callbacks) return true;
if (!callback) { this.events[eventName] = []; return true; }
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i] === callback) {
this.events[eventName].splice(i, 1);
return true;
}
}
return false;
},
dispatchEvent: function (eventName) {
var i,
args,
callbacks = this.events[eventName];
if (callbacks) {
args = Array.prototype.slice.call(arguments, 1);
for (i = 0; i < callbacks.length; i++) {
callbacks[i].apply(null, args);
}
}
},
// end: fake events
// fake DOM attribute methods
attributes: {},
hasAttribute: function(name){
return (name in this.attributes);
},
removeAttribute: function(name){
delete this.attributes[name];
},
getAttribute: function(name){
if (this.hasAttribute(name)) {
return this.attributes[name];
}
return '';
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
remove: function() {
mejs.Utility.removeSwf(this.pluginElement.id);
}
};
// Handles calls from Flash/Silverlight and reports them as native <video/audio> events and properties
mejs.MediaPluginBridge = {
pluginMediaElements:{},
htmlMediaElements:{},
registerPluginElement: function (id, pluginMediaElement, htmlMediaElement) {
this.pluginMediaElements[id] = pluginMediaElement;
this.htmlMediaElements[id] = htmlMediaElement;
},
// when Flash/Silverlight is ready, it calls out to this method
initPlugin: function (id) {
var pluginMediaElement = this.pluginMediaElements[id],
htmlMediaElement = this.htmlMediaElements[id];
if (pluginMediaElement) {
// find the javascript bridge
switch (pluginMediaElement.pluginType) {
case "flash":
pluginMediaElement.pluginElement = pluginMediaElement.pluginApi = document.getElementById(id);
break;
case "silverlight":
pluginMediaElement.pluginElement = document.getElementById(pluginMediaElement.id);
pluginMediaElement.pluginApi = pluginMediaElement.pluginElement.Content.MediaElementJS;
break;
}
if (pluginMediaElement.pluginApi != null && pluginMediaElement.success) {
pluginMediaElement.success(pluginMediaElement, htmlMediaElement);
}
}
},
// receives events from Flash/Silverlight and sends them out as HTML5 media events
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html
fireEvent: function (id, eventName, values) {
var
e,
i,
bufferedTime,
pluginMediaElement = this.pluginMediaElements[id];
pluginMediaElement.ended = false;
pluginMediaElement.paused = true;
// fake event object to mimic real HTML media event.
e = {
type: eventName,
target: pluginMediaElement
};
// attach all values to element and event object
for (i in values) {
pluginMediaElement[i] = values[i];
e[i] = values[i];
}
// fake the newer W3C buffered TimeRange (loaded and total have been removed)
bufferedTime = values.bufferedTime || 0;
e.target.buffered = e.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
pluginMediaElement.dispatchEvent(e.type, e);
}
};
/*
Default options
*/
mejs.MediaElementDefaults = {
// allows testing on HTML5, flash, silverlight
// auto: attempts to detect what the browser can do
// native: forces HTML5 playback
// shim: disallows HTML5, will attempt either Flash or Silverlight
// none: forces fallback view
mode: 'auto',
// remove or reorder to change plugin priority and availability
plugins: ['flash','silverlight','youtube','vimeo'],
// shows debug errors on screen
enablePluginDebug: false,
// overrides the type specified, useful for dynamic instantiation
type: '',
// path to Flash and Silverlight plugins
pluginPath: mejs.Utility.getScriptPath(['mediaelement.js','mediaelement.min.js','mediaelement-and-player.js','mediaelement-and-player.min.js']),
// name of flash file
flashName: 'flashmediaelement.swf',
// turns on the smoothing filter in Flash
enablePluginSmoothing: false,
// name of silverlight file
silverlightName: 'silverlightmediaelement.xap',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// overrides <video width>
pluginWidth: -1,
// overrides <video height>
pluginHeight: -1,
// additional plugin variables in 'key=value' form
pluginVars: [],
// rate in milliseconds for Flash and Silverlight to fire the timeupdate event
// larger number is less accurate, but less strain on plugin->JavaScript bridge
timerRate: 250,
// initial volume for player
startVolume: 0.8,
success: function () { },
error: function () { }
};
/*
Determines if a browser supports the <video> or <audio> element
and returns either the native element or a Flash/Silverlight version that
mimics HTML5 MediaElement
*/
mejs.MediaElement = function (el, o) {
return mejs.HtmlMediaElementShim.create(el,o);
};
mejs.HtmlMediaElementShim = {
create: function(el, o) {
var
options = mejs.MediaElementDefaults,
htmlMediaElement = (typeof(el) == 'string') ? document.getElementById(el) : el,
tagName = htmlMediaElement.tagName.toLowerCase(),
isMediaTag = (tagName === 'audio' || tagName === 'video'),
src = (isMediaTag) ? htmlMediaElement.getAttribute('src') : htmlMediaElement.getAttribute('href'),
poster = htmlMediaElement.getAttribute('poster'),
autoplay = htmlMediaElement.getAttribute('autoplay'),
preload = htmlMediaElement.getAttribute('preload'),
controls = htmlMediaElement.getAttribute('controls'),
playback,
prop;
// extend options
for (prop in o) {
options[prop] = o[prop];
}
// clean up attributes
src = (typeof src == 'undefined' || src === null || src == '') ? null : src;
poster = (typeof poster == 'undefined' || poster === null) ? '' : poster;
preload = (typeof preload == 'undefined' || preload === null || preload === 'false') ? 'none' : preload;
autoplay = !(typeof autoplay == 'undefined' || autoplay === null || autoplay === 'false');
controls = !(typeof controls == 'undefined' || controls === null || controls === 'false');
// test for HTML5 and plugin capabilities
playback = this.determinePlayback(htmlMediaElement, options, mejs.MediaFeatures.supportsMediaTag, isMediaTag, src);
playback.url = (playback.url !== null) ? mejs.Utility.absolutizeUrl(playback.url) : '';
if (playback.method == 'native') {
// second fix for android
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.src = playback.url;
htmlMediaElement.addEventListener('click', function() {
htmlMediaElement.play();
}, false);
}
// add methods to native HTMLMediaElement
return this.updateNative(playback, options, autoplay, preload);
} else if (playback.method !== '') {
// create plugin to mimic HTMLMediaElement
return this.createPlugin( playback, options, poster, autoplay, preload, controls);
} else {
// boo, no HTML5, no Flash, no Silverlight.
this.createErrorMessage( playback, options, poster );
return this;
}
},
determinePlayback: function(htmlMediaElement, options, supportsMediaTag, isMediaTag, src) {
var
mediaFiles = [],
i,
j,
k,
l,
n,
type,
result = { method: '', url: '', htmlMediaElement: htmlMediaElement, isVideo: (htmlMediaElement.tagName.toLowerCase() != 'audio')},
pluginName,
pluginVersions,
pluginInfo,
dummy;
// STEP 1: Get URL and type from <video src> or <source src>
// supplied type overrides <video type> and <source type>
if (typeof options.type != 'undefined' && options.type !== '') {
// accept either string or array of types
if (typeof options.type == 'string') {
mediaFiles.push({type:options.type, url:src});
} else {
for (i=0; i<options.type.length; i++) {
mediaFiles.push({type:options.type[i], url:src});
}
}
// test for src attribute first
} else if (src !== null) {
type = this.formatType(src, htmlMediaElement.getAttribute('type'));
mediaFiles.push({type:type, url:src});
// then test for <source> elements
} else {
// test <source> types to see if they are usable
for (i = 0; i < htmlMediaElement.childNodes.length; i++) {
n = htmlMediaElement.childNodes[i];
if (n.nodeType == 1 && n.tagName.toLowerCase() == 'source') {
src = n.getAttribute('src');
type = this.formatType(src, n.getAttribute('type'));
mediaFiles.push({type:type, url:src});
}
}
}
// in the case of dynamicly created players
// check for audio types
if (!isMediaTag && mediaFiles.length > 0 && mediaFiles[0].url !== null && this.getTypeFromFile(mediaFiles[0].url).indexOf('audio') > -1) {
result.isVideo = false;
}
// STEP 2: Test for playback method
// special case for Android which sadly doesn't implement the canPlayType function (always returns '')
if (mejs.MediaFeatures.isBustedAndroid) {
htmlMediaElement.canPlayType = function(type) {
return (type.match(/video\/(mp4|m4v)/gi) !== null) ? 'maybe' : '';
};
}
// test for native playback first
if (supportsMediaTag && (options.mode === 'auto' || options.mode === 'native')) {
if (!isMediaTag) {
// create a real HTML5 Media Element
dummy = document.createElement( result.isVideo ? 'video' : 'audio');
htmlMediaElement.parentNode.insertBefore(dummy, htmlMediaElement);
htmlMediaElement.style.display = 'none';
// use this one from now on
result.htmlMediaElement = htmlMediaElement = dummy;
}
for (i=0; i<mediaFiles.length; i++) {
// normal check
if (htmlMediaElement.canPlayType(mediaFiles[i].type).replace(/no/, '') !== ''
// special case for Mac/Safari 5.0.3 which answers '' to canPlayType('audio/mp3') but 'maybe' to canPlayType('audio/mpeg')
|| htmlMediaElement.canPlayType(mediaFiles[i].type.replace(/mp3/,'mpeg')).replace(/no/, '') !== '') {
result.method = 'native';
result.url = mediaFiles[i].url;
break;
}
}
if (result.method === 'native') {
if (result.url !== null) {
htmlMediaElement.src = result.url;
}
return result;
}
}
// if native playback didn't work, then test plugins
if (options.mode === 'auto' || options.mode === 'shim') {
for (i=0; i<mediaFiles.length; i++) {
type = mediaFiles[i].type;
// test all plugins in order of preference [silverlight, flash]
for (j=0; j<options.plugins.length; j++) {
pluginName = options.plugins[j];
// test version of plugin (for future features)
pluginVersions = mejs.plugins[pluginName];
for (k=0; k<pluginVersions.length; k++) {
pluginInfo = pluginVersions[k];
// test if user has the correct plugin version
// for youtube/vimeo
if (pluginInfo.version == null ||
mejs.PluginDetector.hasPluginVersion(pluginName, pluginInfo.version)) {
// test for plugin playback types
for (l=0; l<pluginInfo.types.length; l++) {
// find plugin that can play the type
if (type == pluginInfo.types[l]) {
result.method = pluginName;
result.url = mediaFiles[i].url;
return result;
}
}
}
}
}
}
}
// what if there's nothing to play? just grab the first available
if (result.method === '' && mediaFiles.length > 0) {
result.url = mediaFiles[0].url;
}
return result;
},
formatType: function(url, type) {
var ext;
// if no type is supplied, fake it with the extension
if (url && !type) {
return this.getTypeFromFile(url);
} else {
// only return the mime part of the type in case the attribute contains the codec
// see http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#the-source-element
// `video/mp4; codecs="avc1.42E01E, mp4a.40.2"` becomes `video/mp4`
if (type && ~type.indexOf(';')) {
return type.substr(0, type.indexOf(';'));
} else {
return type;
}
}
},
getTypeFromFile: function(url) {
var ext = url.substring(url.lastIndexOf('.') + 1);
return (/(mp4|m4v|ogg|ogv|webm|flv|wmv|mpeg|mov)/gi.test(ext) ? 'video' : 'audio') + '/' + ext;
},
createErrorMessage: function(playback, options, poster) {
var
htmlMediaElement = playback.htmlMediaElement,
errorContainer = document.createElement('div');
errorContainer.className = 'me-cannotplay';
try {
errorContainer.style.width = htmlMediaElement.width + 'px';
errorContainer.style.height = htmlMediaElement.height + 'px';
} catch (e) {}
errorContainer.innerHTML = (poster !== '') ?
'<a href="' + playback.url + '"><img src="' + poster + '" width="100%" height="100%" /></a>' :
'<a href="' + playback.url + '"><span>Download File</span></a>';
htmlMediaElement.parentNode.insertBefore(errorContainer, htmlMediaElement);
htmlMediaElement.style.display = 'none';
options.error(htmlMediaElement);
},
createPlugin:function(playback, options, poster, autoplay, preload, controls) {
var
htmlMediaElement = playback.htmlMediaElement,
width = 1,
height = 1,
pluginid = 'me_' + playback.method + '_' + (mejs.meIndex++),
pluginMediaElement = new mejs.PluginMediaElement(pluginid, playback.method, playback.url),
container = document.createElement('div'),
specialIEContainer,
node,
initVars;
// copy tagName from html media element
pluginMediaElement.tagName = htmlMediaElement.tagName
// copy attributes from html media element to plugin media element
for (var i = 0; i < htmlMediaElement.attributes.length; i++) {
var attribute = htmlMediaElement.attributes[i];
if (attribute.specified == true) {
pluginMediaElement.setAttribute(attribute.name, attribute.value);
}
}
// check for placement inside a <p> tag (sometimes WYSIWYG editors do this)
node = htmlMediaElement.parentNode;
while (node !== null && node.tagName.toLowerCase() != 'body') {
if (node.parentNode.tagName.toLowerCase() == 'p') {
node.parentNode.parentNode.insertBefore(node, node.parentNode);
break;
}
node = node.parentNode;
}
if (playback.isVideo) {
width = (options.videoWidth > 0) ? options.videoWidth : (htmlMediaElement.getAttribute('width') !== null) ? htmlMediaElement.getAttribute('width') : options.defaultVideoWidth;
height = (options.videoHeight > 0) ? options.videoHeight : (htmlMediaElement.getAttribute('height') !== null) ? htmlMediaElement.getAttribute('height') : options.defaultVideoHeight;
// in case of '%' make sure it's encoded
width = mejs.Utility.encodeUrl(width);
height = mejs.Utility.encodeUrl(height);
} else {
if (options.enablePluginDebug) {
width = 320;
height = 240;
}
}
// register plugin
pluginMediaElement.success = options.success;
mejs.MediaPluginBridge.registerPluginElement(pluginid, pluginMediaElement, htmlMediaElement);
// add container (must be added to DOM before inserting HTML for IE)
container.className = 'me-plugin';
container.id = pluginid + '_container';
if (playback.isVideo) {
htmlMediaElement.parentNode.insertBefore(container, htmlMediaElement);
} else {
document.body.insertBefore(container, document.body.childNodes[0]);
}
// flash/silverlight vars
initVars = [
'id=' + pluginid,
'isvideo=' + ((playback.isVideo) ? "true" : "false"),
'autoplay=' + ((autoplay) ? "true" : "false"),
'preload=' + preload,
'width=' + width,
'startvolume=' + options.startVolume,
'timerrate=' + options.timerRate,
'height=' + height];
if (playback.url !== null) {
if (playback.method == 'flash') {
initVars.push('file=' + mejs.Utility.encodeUrl(playback.url));
} else {
initVars.push('file=' + playback.url);
}
}
if (options.enablePluginDebug) {
initVars.push('debug=true');
}
if (options.enablePluginSmoothing) {
initVars.push('smoothing=true');
}
if (controls) {
initVars.push('controls=true'); // shows controls in the plugin if desired
}
if (options.pluginVars) {
initVars = initVars.concat(options.pluginVars);
}
switch (playback.method) {
case 'silverlight':
container.innerHTML =
'<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" id="' + pluginid + '" name="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="initParams" value="' + initVars.join(',') + '" />' +
'<param name="windowless" value="true" />' +
'<param name="background" value="black" />' +
'<param name="minRuntimeVersion" value="3.0.0.0" />' +
'<param name="autoUpgrade" value="true" />' +
'<param name="source" value="' + options.pluginPath + options.silverlightName + '" />' +
'</object>';
break;
case 'flash':
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
container.appendChild(specialIEContainer);
specialIEContainer.outerHTML =
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + pluginid + '" width="' + width + '" height="' + height + '">' +
'<param name="movie" value="' + options.pluginPath + options.flashName + '?x=' + (new Date()) + '" />' +
'<param name="flashvars" value="' + initVars.join('&') + '" />' +
'<param name="quality" value="high" />' +
'<param name="bgcolor" value="#000000" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
container.innerHTML =
'<embed id="' + pluginid + '" name="' + pluginid + '" ' +
'play="true" ' +
'loop="false" ' +
'quality="high" ' +
'bgcolor="#000000" ' +
'wmode="transparent" ' +
'allowScriptAccess="always" ' +
'allowFullScreen="true" ' +
'type="application/x-shockwave-flash" pluginspage="//www.macromedia.com/go/getflashplayer" ' +
'src="' + options.pluginPath + options.flashName + '" ' +
'flashvars="' + initVars.join('&') + '" ' +
'width="' + width + '" ' +
'height="' + height + '"></embed>';
}
break;
case 'youtube':
var
videoId = playback.url.substr(playback.url.lastIndexOf('=')+1);
youtubeSettings = {
container: container,
containerId: container.id,
pluginMediaElement: pluginMediaElement,
pluginId: pluginid,
videoId: videoId,
height: height,
width: width
};
if (mejs.PluginDetector.hasPluginVersion('flash', [10,0,0]) ) {
mejs.YouTubeApi.createFlash(youtubeSettings);
} else {
mejs.YouTubeApi.enqueueIframe(youtubeSettings);
}
break;
// DEMO Code. Does NOT work.
case 'vimeo':
console.log('vimeoid');
pluginMediaElement.vimeoid = playback.url.substr(playback.url.lastIndexOf('/')+1);
container.innerHTML =
'<object width="' + width + '" height="' + height + '">' +
'<param name="allowfullscreen" value="true" />' +
'<param name="allowscriptaccess" value="always" />' +
'<param name="flashvars" value="api=1" />' +
'<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" />' +
'<embed src="//vimeo.com/moogaloop.swf?api=1&clip_id=' + pluginMediaElement.vimeoid + '&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1&autoplay=0&loop=0" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>' +
'</object>';
break;
}
// hide original element
htmlMediaElement.style.display = 'none';
// FYI: options.success will be fired by the MediaPluginBridge
return pluginMediaElement;
},
updateNative: function(playback, options, autoplay, preload) {
var htmlMediaElement = playback.htmlMediaElement,
m;
// add methods to video object to bring it into parity with Flash Object
for (m in mejs.HtmlMediaElement) {
htmlMediaElement[m] = mejs.HtmlMediaElement[m];
}
/*
Chrome now supports preload="none"
if (mejs.MediaFeatures.isChrome) {
// special case to enforce preload attribute (Chrome doesn't respect this)
if (preload === 'none' && !autoplay) {
// forces the browser to stop loading (note: fails in IE9)
htmlMediaElement.src = '';
htmlMediaElement.load();
htmlMediaElement.canceledPreload = true;
htmlMediaElement.addEventListener('play',function() {
if (htmlMediaElement.canceledPreload) {
htmlMediaElement.src = playback.url;
htmlMediaElement.load();
htmlMediaElement.play();
htmlMediaElement.canceledPreload = false;
}
}, false);
// for some reason Chrome forgets how to autoplay sometimes.
} else if (autoplay) {
htmlMediaElement.load();
htmlMediaElement.play();
}
}
*/
// fire success code
options.success(htmlMediaElement, htmlMediaElement);
return htmlMediaElement;
}
};
/*
- test on IE (object vs. embed)
- determine when to use iframe (Firefox, Safari, Mobile) vs. Flash (Chrome, IE)
- fullscreen?
*/
// YouTube Flash and Iframe API
mejs.YouTubeApi = {
isIframeStarted: false,
isIframeLoaded: false,
loadIframeApi: function() {
if (!this.isIframeStarted) {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
this.isIframeStarted = true;
}
},
iframeQueue: [],
enqueueIframe: function(yt) {
if (this.isLoaded) {
this.createIframe(yt);
} else {
this.loadIframeApi();
this.iframeQueue.push(yt);
}
},
createIframe: function(settings) {
var
pluginMediaElement = settings.pluginMediaElement,
player = new YT.Player(settings.containerId, {
height: settings.height,
width: settings.width,
videoId: settings.videoId,
playerVars: {controls:0},
events: {
'onReady': function() {
// hook up iframe object to MEjs
settings.pluginMediaElement.pluginApi = player;
// init mejs
mejs.MediaPluginBridge.initPlugin(settings.pluginId);
// create timer
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
'onStateChange': function(e) {
mejs.YouTubeApi.handleStateChange(e.data, player, pluginMediaElement);
}
}
});
},
createEvent: function (player, pluginMediaElement, eventName) {
var obj = {
type: eventName,
target: pluginMediaElement
};
if (player && player.getDuration) {
// time
pluginMediaElement.currentTime = obj.currentTime = player.getCurrentTime();
pluginMediaElement.duration = obj.duration = player.getDuration();
// state
obj.paused = pluginMediaElement.paused;
obj.ended = pluginMediaElement.ended;
// sound
obj.muted = player.isMuted();
obj.volume = player.getVolume() / 100;
// progress
obj.bytesTotal = player.getVideoBytesTotal();
obj.bufferedBytes = player.getVideoBytesLoaded();
// fake the W3C buffered TimeRange
var bufferedTime = obj.bufferedBytes / obj.bytesTotal * obj.duration;
obj.target.buffered = obj.buffered = {
start: function(index) {
return 0;
},
end: function (index) {
return bufferedTime;
},
length: 1
};
}
// send event up the chain
pluginMediaElement.dispatchEvent(obj.type, obj);
},
iFrameReady: function() {
this.isLoaded = true;
this.isIframeLoaded = true;
while (this.iframeQueue.length > 0) {
var settings = this.iframeQueue.pop();
this.createIframe(settings);
}
},
// FLASH!
flashPlayers: {},
createFlash: function(settings) {
this.flashPlayers[settings.pluginId] = settings;
/*
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
*/
var specialIEContainer,
youtubeUrl = 'http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=' + settings.pluginId + '&version=3&autoplay=0&controls=0&modestbranding=1&loop=0';
if (mejs.MediaFeatures.isIE) {
specialIEContainer = document.createElement('div');
settings.container.appendChild(specialIEContainer);
specialIEContainer.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" ' +
'id="' + settings.pluginId + '" width="' + settings.width + '" height="' + settings.height + '">' +
'<param name="movie" value="' + youtubeUrl + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowScriptAccess" value="always" />' +
'<param name="allowFullScreen" value="true" />' +
'</object>';
} else {
settings.container.innerHTML =
'<object type="application/x-shockwave-flash" id="' + settings.pluginId + '" data="' + youtubeUrl + '" ' +
'width="' + settings.width + '" height="' + settings.height + '" style="visibility: visible; ">' +
'<param name="allowScriptAccess" value="always">' +
'<param name="wmode" value="transparent">' +
'</object>';
}
},
flashReady: function(id) {
var
settings = this.flashPlayers[id],
player = document.getElementById(id),
pluginMediaElement = settings.pluginMediaElement;
// hook up and return to MediaELementPlayer.success
pluginMediaElement.pluginApi =
pluginMediaElement.pluginElement = player;
mejs.MediaPluginBridge.initPlugin(id);
// load the youtube video
player.cueVideoById(settings.videoId);
var callbackName = settings.containerId + '_callback'
window[callbackName] = function(e) {
mejs.YouTubeApi.handleStateChange(e, player, pluginMediaElement);
}
player.addEventListener('onStateChange', callbackName);
setInterval(function() {
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'timeupdate');
}, 250);
},
handleStateChange: function(youTubeState, player, pluginMediaElement) {
switch (youTubeState) {
case -1: // not started
pluginMediaElement.paused = true;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'loadedmetadata');
//createYouTubeEvent(player, pluginMediaElement, 'loadeddata');
break;
case 0:
pluginMediaElement.paused = false;
pluginMediaElement.ended = true;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'ended');
break;
case 1:
pluginMediaElement.paused = false;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'play');
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'playing');
break;
case 2:
pluginMediaElement.paused = true;
pluginMediaElement.ended = false;
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'pause');
break;
case 3: // buffering
mejs.YouTubeApi.createEvent(player, pluginMediaElement, 'progress');
break;
case 5:
// cued?
break;
}
}
}
// IFRAME
function onYouTubePlayerAPIReady() {
mejs.YouTubeApi.iFrameReady();
}
// FLASH
function onYouTubePlayerReady(id) {
mejs.YouTubeApi.flashReady(id);
}
window.mejs = mejs;
window.MediaElement = mejs.MediaElement;
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2012, John Dyer (http://j.hn/)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*/
if (typeof jQuery != 'undefined') {
mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
mejs.$ = ender;
}
(function ($) {
// default player values
mejs.MepDefaults = {
// url to poster (to fix iOS 3.x)
poster: '',
// default if the <video width> is not specified
defaultVideoWidth: 480,
// default if the <video height> is not specified
defaultVideoHeight: 270,
// if set, overrides <video width>
videoWidth: -1,
// if set, overrides <video height>
videoHeight: -1,
// default if the user doesn't specify
defaultAudioWidth: 400,
// default if the user doesn't specify
defaultAudioHeight: 30,
// width of audio player
audioWidth: -1,
// height of audio player
audioHeight: -1,
// initial volume when the player starts (overrided by user cookie)
startVolume: 0.8,
// useful for <audio> player loops
loop: false,
// resize to media dimensions
enableAutosize: true,
// forces the hour marker (##:00:00)
alwaysShowHours: false,
// show framecount in timecode (##:00:00:00)
showTimecodeFrameCount: false,
// used when showTimecodeFrameCount is set to true
framesPerSecond: 25,
// automatically calculate the width of the progress bar based on the sizes of other elements
autosizeProgress : true,
// Hide controls when playing and mouse is not over the video
alwaysShowControls: false,
// force iPad's native controls
iPadUseNativeControls: false,
// force iPhone's native controls
iPhoneUseNativeControls: false,
// force Android's native controls
AndroidUseNativeControls: false,
// features to show
features: ['playpause','current','progress','duration','tracks','volume','fullscreen'],
// only for dynamic
isVideo: true,
// turns keyboard support on and off for this instance
enableKeyboard: true,
// whenthis player starts, it will pause other players
pauseOtherPlayers: true,
// array of keyboard actions such as play pause
keyActions: [
{
keys: [
32, // SPACE
179 // GOOGLE play/pause button
],
action: function(player, media) {
if (media.paused || media.ended) {
media.play();
} else {
media.pause();
}
}
},
{
keys: [38], // UP
action: function(player, media) {
var newVolume = Math.min(media.volume + 0.1, 1);
media.setVolume(newVolume);
}
},
{
keys: [40], // DOWN
action: function(player, media) {
var newVolume = Math.max(media.volume - 0.1, 0);
media.setVolume(newVolume);
}
},
{
keys: [
37, // LEFT
227 // Google TV rewind
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.max(media.currentTime - (media.duration * 0.05), 0);
media.setCurrentTime(newTime);
}
}
},
{
keys: [
39, // RIGHT
228 // Google TV forward
],
action: function(player, media) {
if (!isNaN(media.duration) && media.duration > 0) {
if (player.isVideo) {
player.showControls();
player.startControlsTimer();
}
// 5%
var newTime = Math.min(media.currentTime + (media.duration * 0.05), media.duration);
media.setCurrentTime(newTime);
}
}
},
{
keys: [70], // f
action: function(player, media) {
if (typeof player.enterFullScreen != 'undefined') {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
}
]
};
mejs.mepIndex = 0;
mejs.players = [];
// wraps a MediaElement object in player controls
mejs.MediaElementPlayer = function(node, o) {
// enforce object, even without "new" (via John Resig)
if ( !(this instanceof mejs.MediaElementPlayer) ) {
return new mejs.MediaElementPlayer(node, o);
}
var t = this;
// these will be reset after the MediaElement.success fires
t.$media = t.$node = $(node);
t.node = t.media = t.$media[0];
// check for existing player
if (typeof t.node.player != 'undefined') {
return t.node.player;
} else {
// attach player to DOM node for reference
t.node.player = t;
}
// try to get options from data-mejsoptions
if (typeof o == 'undefined') {
o = t.$node.data('mejsoptions');
}
// extend default options
t.options = $.extend({},mejs.MepDefaults,o);
// add to player array (for focus events)
mejs.players.push(t);
// start up
t.init();
return t;
};
// actual player
mejs.MediaElementPlayer.prototype = {
hasFocus: false,
controlsAreVisible: true,
init: function() {
var
t = this,
mf = mejs.MediaFeatures,
// options for MediaElement (shim)
meOptions = $.extend(true, {}, t.options, {
success: function(media, domNode) { t.meReady(media, domNode); },
error: function(e) { t.handleError(e);}
}),
tagName = t.media.tagName.toLowerCase();
t.isDynamic = (tagName !== 'audio' && tagName !== 'video');
if (t.isDynamic) {
// get video from src or href?
t.isVideo = t.options.isVideo;
} else {
t.isVideo = (tagName !== 'audio' && t.options.isVideo);
}
// use native controls in iPad, iPhone, and Android
if ((mf.isiPad && t.options.iPadUseNativeControls) || (mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// add controls and stop
t.$media.attr('controls', 'controls');
// attempt to fix iOS 3 bug
//t.$media.removeAttr('poster');
// no Issue found on iOS3 -ttroxell
// override Apple's autoplay override for iPads
if (mf.isiPad && t.media.getAttribute('autoplay') !== null) {
t.media.load();
t.media.play();
}
} else if (mf.isAndroid && t.AndroidUseNativeControls) {
// leave default player
} else {
// DESKTOP: use MediaElementPlayer controls
// remove native controls
t.$media.removeAttr('controls');
// unique ID
t.id = 'mep_' + mejs.mepIndex++;
// build container
t.container =
$('<div id="' + t.id + '" class="mejs-container">'+
'<div class="mejs-inner">'+
'<div class="mejs-mediaelement"></div>'+
'<div class="mejs-layers"></div>'+
'<div class="mejs-controls"></div>'+
'<div class="mejs-clear"></div>'+
'</div>' +
'</div>')
.addClass(t.$media[0].className)
.insertBefore(t.$media);
// add classes for user and content
t.container.addClass(
(mf.isAndroid ? 'mejs-android ' : '') +
(mf.isiOS ? 'mejs-ios ' : '') +
(mf.isiPad ? 'mejs-ipad ' : '') +
(mf.isiPhone ? 'mejs-iphone ' : '') +
(t.isVideo ? 'mejs-video ' : 'mejs-audio ')
);
// move the <video/video> tag into the right spot
if (mf.isiOS) {
// sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
var $newMedia = t.$media.clone();
t.container.find('.mejs-mediaelement').append($newMedia);
t.$media.remove();
t.$node = t.$media = $newMedia;
t.node = t.media = $newMedia[0]
} else {
// normal way of moving it into place (doesn't work on iOS)
t.container.find('.mejs-mediaelement').append(t.$media);
}
// find parts
t.controls = t.container.find('.mejs-controls');
t.layers = t.container.find('.mejs-layers');
// determine the size
/* size priority:
(1) videoWidth (forced),
(2) style="width;height;"
(3) width attribute,
(4) defaultVideoWidth (for unspecified cases)
*/
var capsTagName = tagName.substring(0,1).toUpperCase() + tagName.substring(1);
if (t.options[tagName + 'Width'] > 0 || t.options[tagName + 'Width'].toString().indexOf('%') > -1) {
t.width = t.options[tagName + 'Width'];
} else if (t.media.style.width !== '' && t.media.style.width !== null) {
t.width = t.media.style.width;
} else if (t.media.getAttribute('width') !== null) {
t.width = t.$media.attr('width');
} else {
t.width = t.options['default' + capsTagName + 'Width'];
}
if (t.options[tagName + 'Height'] > 0 || t.options[tagName + 'Height'].toString().indexOf('%') > -1) {
t.height = t.options[tagName + 'Height'];
} else if (t.media.style.height !== '' && t.media.style.height !== null) {
t.height = t.media.style.height;
} else if (t.$media[0].getAttribute('height') !== null) {
t.height = t.$media.attr('height');
} else {
t.height = t.options['default' + capsTagName + 'Height'];
}
// set the size, while we wait for the plugins to load below
t.setPlayerSize(t.width, t.height);
// create MediaElementShim
meOptions.pluginWidth = t.height;
meOptions.pluginHeight = t.width;
}
// create MediaElement shim
mejs.MediaElement(t.$media[0], meOptions);
},
showControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (t.controlsAreVisible)
return;
if (doAnimation) {
t.controls
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});
} else {
t.controls
.css('visibility','visible')
.css('display','block');
// any additional controls people might add and want to hide
t.container.find('.mejs-control')
.css('visibility','visible')
.css('display','block');
t.controlsAreVisible = true;
}
t.setControlsSize();
},
hideControls: function(doAnimation) {
var t = this;
doAnimation = typeof doAnimation == 'undefined' || doAnimation;
if (!t.controlsAreVisible)
return;
if (doAnimation) {
// fade out main controls
t.controls.stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
});
// any additional controls people might add and want to hide
t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
$(this)
.css('visibility','hidden')
.css('display','block');
});
} else {
// hide main controls
t.controls
.css('visibility','hidden')
.css('display','block');
// hide others
t.container.find('.mejs-control')
.css('visibility','hidden')
.css('display','block');
t.controlsAreVisible = false;
}
},
controlsTimer: null,
startControlsTimer: function(timeout) {
var t = this;
timeout = typeof timeout != 'undefined' ? timeout : 1500;
t.killControlsTimer('start');
t.controlsTimer = setTimeout(function() {
//console.log('timer fired');
t.hideControls();
t.killControlsTimer('hide');
}, timeout);
},
killControlsTimer: function(src) {
var t = this;
if (t.controlsTimer !== null) {
clearTimeout(t.controlsTimer);
delete t.controlsTimer;
t.controlsTimer = null;
}
},
controlsEnabled: true,
disableControls: function() {
var t= this;
t.killControlsTimer();
t.hideControls(false);
this.controlsEnabled = false;
},
enableControls: function() {
var t= this;
t.showControls(false);
t.controlsEnabled = true;
},
// Sets up all controls and events
meReady: function(media, domNode) {
var t = this,
mf = mejs.MediaFeatures,
autoplayAttr = domNode.getAttribute('autoplay'),
autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
featureIndex,
feature;
// make sure it can't create itself again if a plugin reloads
if (t.created)
return;
else
t.created = true;
t.media = media;
t.domNode = domNode;
if (!(mf.isAndroid && t.options.AndroidUseNativeControls) && !(mf.isiPad && t.options.iPadUseNativeControls) && !(mf.isiPhone && t.options.iPhoneUseNativeControls)) {
// two built in features
t.buildposter(t, t.controls, t.layers, t.media);
t.buildkeyboard(t, t.controls, t.layers, t.media);
t.buildoverlays(t, t.controls, t.layers, t.media);
// grab for use by features
t.findTracks();
// add user-defined features/controls
for (featureIndex in t.options.features) {
feature = t.options.features[featureIndex];
if (t['build' + feature]) {
try {
t['build' + feature](t, t.controls, t.layers, t.media);
} catch (e) {
// TODO: report control error
//throw e;
//console.log('error building ' + feature);
//console.log(e);
}
}
}
t.container.trigger('controlsready');
// reset all layers and controls
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
// controls fade
if (t.isVideo) {
if (mejs.MediaFeatures.hasTouch) {
// for touch devices (iOS, Android)
// show/hide without animation on touch
t.$media.bind('touchstart', function() {
// toggle controls
if (t.controlsAreVisible) {
t.hideControls(false);
} else {
if (t.controlsEnabled) {
t.showControls(false);
}
}
});
} else {
// click controls
var clickElement = (t.media.pluginType == 'native') ? t.$media : $(t.media.pluginElement);
// click to play/pause
clickElement.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
// show/hide controls
t.container
.bind('mouseenter mouseover', function () {
if (t.controlsEnabled) {
if (!t.options.alwaysShowControls) {
t.killControlsTimer('enter');
t.showControls();
t.startControlsTimer(2500);
}
}
})
.bind('mousemove', function() {
if (t.controlsEnabled) {
if (!t.controlsAreVisible) {
t.showControls();
}
//t.killControlsTimer('move');
if (!t.options.alwaysShowControls) {
t.startControlsTimer(2500);
}
}
})
.bind('mouseleave', function () {
if (t.controlsEnabled) {
if (!t.media.paused && !t.options.alwaysShowControls) {
t.startControlsTimer(1000);
}
}
});
}
// check for autoplay
if (autoplay && !t.options.alwaysShowControls) {
t.hideControls();
}
// resizer
if (t.options.enableAutosize) {
t.media.addEventListener('loadedmetadata', function(e) {
// if the <video height> was not set and the options.videoHeight was not set
// then resize to the real dimensions
if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
t.setControlsSize();
t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
}
}, false);
}
}
// EVENTS
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
// go through all other players
for (var i=0, il=mejs.players.length; i<il; i++) {
var p = mejs.players[i];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
// ended for all
t.media.addEventListener('ended', function (e) {
try{
t.media.setCurrentTime(0);
} catch (exp) {
}
t.media.pause();
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
if (t.options.loop) {
t.media.play();
} else if (!t.options.alwaysShowControls && t.controlsEnabled) {
t.showControls();
}
}, false);
// resize on the first play
t.media.addEventListener('loadedmetadata', function(e) {
if (t.updateDuration) {
t.updateDuration();
}
if (t.updateCurrent) {
t.updateCurrent();
}
if (!t.isFullScreen) {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}
}, false);
// webkit has trouble doing this without a delay
setTimeout(function () {
t.setPlayerSize(t.width, t.height);
t.setControlsSize();
}, 50);
// adjust controls whenever window sizes (used to be in fullscreen only)
$(window).resize(function() {
// don't resize for fullscreen mode
if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
t.setPlayerSize(t.width, t.height);
}
// always adjust controls
t.setControlsSize();
});
// TEMP: needs to be moved somewhere else
if (t.media.pluginType == 'youtube') {
t.container.find('.mejs-overlay-play').hide();
}
}
// force autoplay for HTML5
if (autoplay && media.pluginType == 'native') {
media.load();
media.play();
}
if (t.options.success) {
if (typeof t.options.success == 'string') {
window[t.options.success](t.media, t.domNode, t);
} else {
t.options.success(t.media, t.domNode, t);
}
}
},
handleError: function(e) {
var t = this;
t.controls.hide();
// Tell user that the file cannot be played
if (t.options.error) {
t.options.error(e);
}
},
setPlayerSize: function(width,height) {
var t = this;
if (typeof width != 'undefined')
t.width = width;
if (typeof height != 'undefined')
t.height = height;
// detect 100% mode
if (t.height.toString().indexOf('%') > 0) {
// do we have the native dimensions yet?
var
nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
parentWidth = t.container.parent().width(),
newHeight = parseInt(parentWidth * nativeHeight/nativeWidth, 10);
if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
parentWidth = $(window).width();
newHeight = $(window).height();
}
// set outer container size
t.container
.width(parentWidth)
.height(newHeight);
// set native <video>
t.$media
.width('100%')
.height('100%');
// set shims
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
// if shim is ready, send the size to the embeded plugin
if (t.media.setVideoSize)
t.media.setVideoSize(parentWidth, newHeight);
// set the layers
t.layers.children('.mejs-layer')
.width('100%')
.height('100%');
} else {
t.container
.width(t.width)
.height(t.height);
t.layers.children('.mejs-layer')
.width(t.width)
.height(t.height);
}
},
setControlsSize: function() {
var t = this,
usedWidth = 0,
railWidth = 0,
rail = t.controls.find('.mejs-time-rail'),
total = t.controls.find('.mejs-time-total'),
current = t.controls.find('.mejs-time-current'),
loaded = t.controls.find('.mejs-time-loaded'),
others = rail.siblings();
// allow the size to come from custom CSS
if (t.options && !t.options.autosizeProgress) {
// Also, frontends devs can be more flexible
// due the opportunity of absolute positioning.
railWidth = parseInt(rail.css('width'));
}
// attempt to autosize
if (railWidth === 0 || !railWidth) {
// find the size of all the other controls besides the rail
others.each(function() {
if ($(this).css('position') != 'absolute') {
usedWidth += $(this).outerWidth(true);
}
});
// fit the rail into the remaining space
railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
}
// outer area
rail.width(railWidth);
// dark space
total.width(railWidth - (total.outerWidth(true) - total.width()));
if (t.setProgressRail)
t.setProgressRail();
if (t.setCurrentRail)
t.setCurrentRail();
},
buildposter: function(player, controls, layers, media) {
var t = this,
poster =
$('<div class="mejs-poster mejs-layer">' +
'</div>')
.appendTo(layers),
posterUrl = player.$media.attr('poster');
// prioriy goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
if (player.options.poster !== '') {
posterUrl = player.options.poster;
}
// second, try the real poster
if (posterUrl !== '' && posterUrl != null) {
t.setPoster(posterUrl);
} else {
poster.hide();
}
media.addEventListener('play',function() {
poster.hide();
}, false);
},
setPoster: function(url) {
var t = this,
posterDiv = t.container.find('.mejs-poster'),
posterImg = posterDiv.find('img');
if (posterImg.length == 0) {
posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
}
posterImg.attr('src', url);
},
buildoverlays: function(player, controls, layers, media) {
if (!player.isVideo)
return;
var
loading =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-loading"><span></span></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
error =
$('<div class="mejs-overlay mejs-layer">'+
'<div class="mejs-overlay-error"></div>'+
'</div>')
.hide() // start out hidden
.appendTo(layers),
// this needs to come last so it's on top
bigPlay =
$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
'<div class="mejs-overlay-button"></div>'+
'</div>')
.appendTo(layers)
.click(function() {
if (media.paused) {
media.play();
} else {
media.pause();
}
});
/*
if (mejs.MediaFeatures.isiOS || mejs.MediaFeatures.isAndroid) {
bigPlay.remove();
loading.remove();
}
*/
// show/hide big play button
media.addEventListener('play',function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('playing', function() {
bigPlay.hide();
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.hide();
}, false);
media.addEventListener('seeking', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('seeked', function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
media.addEventListener('pause',function() {
if (!mejs.MediaFeatures.isiPhone) {
bigPlay.show();
}
}, false);
media.addEventListener('waiting', function() {
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
// show/hide loading
media.addEventListener('loadeddata',function() {
// for some reason Chrome is firing this event
//if (mejs.MediaFeatures.isChrome && media.getAttribute && media.getAttribute('preload') === 'none')
// return;
loading.show();
controls.find('.mejs-time-buffering').show();
}, false);
media.addEventListener('canplay',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
}, false);
// error handling
media.addEventListener('error',function() {
loading.hide();
controls.find('.mejs-time-buffering').hide();
error.show();
error.find('mejs-overlay-error').html("Error loading this resource");
}, false);
},
buildkeyboard: function(player, controls, layers, media) {
var t = this;
// listen for key presses
$(document).keydown(function(e) {
if (player.hasFocus && player.options.enableKeyboard) {
// find a matching key
for (var i=0, il=player.options.keyActions.length; i<il; i++) {
var keyAction = player.options.keyActions[i];
for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
if (e.keyCode == keyAction.keys[j]) {
e.preventDefault();
keyAction.action(player, media);
return false;
}
}
}
}
return true;
});
// check if someone clicked outside a player region, then kill its focus
$(document).click(function(event) {
if ($(event.target).closest('.mejs-container').length == 0) {
player.hasFocus = false;
}
});
},
findTracks: function() {
var t = this,
tracktags = t.$media.find('track');
// store for use by plugins
t.tracks = [];
tracktags.each(function(index, track) {
track = $(track);
t.tracks.push({
srclang: track.attr('srclang').toLowerCase(),
src: track.attr('src'),
kind: track.attr('kind'),
label: track.attr('label') || '',
entries: [],
isLoaded: false
});
});
},
changeSkin: function(className) {
this.container[0].className = 'mejs-container ' + className;
this.setPlayerSize(this.width, this.height);
this.setControlsSize();
},
play: function() {
this.media.play();
},
pause: function() {
this.media.pause();
},
load: function() {
this.media.load();
},
setMuted: function(muted) {
this.media.setMuted(muted);
},
setCurrentTime: function(time) {
this.media.setCurrentTime(time);
},
getCurrentTime: function() {
return this.media.currentTime;
},
setVolume: function(volume) {
this.media.setVolume(volume);
},
getVolume: function() {
return this.media.volume;
},
setSrc: function(src) {
this.media.setSrc(src);
},
remove: function() {
var t = this;
if (t.media.pluginType == 'flash') {
t.media.remove();
} else if (t.media.pluginType == 'native') {
t.media.prop('controls', true);
}
// grab video and put it back in place
if (!t.isDynamic) {
t.$node.insertBefore(t.container)
}
t.container.remove();
}
};
// turn into jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.mediaelementplayer = function (options) {
return this.each(function () {
new mejs.MediaElementPlayer(this, options);
});
};
}
$(document).ready(function() {
// auto enable using JSON attribute
$('.mejs-player').mediaelementplayer();
});
// push out to window
window.MediaElementPlayer = mejs.MediaElementPlayer;
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
playpauseText: 'Play/Pause'
});
// PLAY/pause BUTTON
$.extend(MediaElementPlayer.prototype, {
buildplaypause: function(player, controls, layers, media) {
var
t = this,
play =
$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function(e) {
e.preventDefault();
if (media.paused) {
media.play();
} else {
media.pause();
}
return false;
});
media.addEventListener('play',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('playing',function() {
play.removeClass('mejs-play').addClass('mejs-pause');
}, false);
media.addEventListener('pause',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
media.addEventListener('paused',function() {
play.removeClass('mejs-pause').addClass('mejs-play');
}, false);
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
stopText: 'Stop'
});
// STOP BUTTON
$.extend(MediaElementPlayer.prototype, {
buildstop: function(player, controls, layers, media) {
var t = this,
stop =
$('<div class="mejs-button mejs-stop-button mejs-stop">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.stopText + '"></button>' +
'</div>')
.appendTo(controls)
.click(function() {
if (!media.paused) {
media.pause();
}
if (media.currentTime > 0) {
media.setCurrentTime(0);
controls.find('.mejs-time-current').width('0px');
controls.find('.mejs-time-handle').css('left', '0px');
controls.find('.mejs-time-float-current').html( mejs.Utility.secondsToTimeCode(0) );
controls.find('.mejs-currenttime').html( mejs.Utility.secondsToTimeCode(0) );
layers.find('.mejs-poster').show();
}
});
}
});
})(mejs.$);
(function($) {
// progress/loaded bar
$.extend(MediaElementPlayer.prototype, {
buildprogress: function(player, controls, layers, media) {
$('<div class="mejs-time-rail">'+
'<span class="mejs-time-total">'+
'<span class="mejs-time-buffering"></span>'+
'<span class="mejs-time-loaded"></span>'+
'<span class="mejs-time-current"></span>'+
'<span class="mejs-time-handle"></span>'+
'<span class="mejs-time-float">' +
'<span class="mejs-time-float-current">00:00</span>' +
'<span class="mejs-time-float-corner"></span>' +
'</span>'+
'</span>'+
'</div>')
.appendTo(controls);
controls.find('.mejs-time-buffering').hide();
var
t = this,
total = controls.find('.mejs-time-total'),
loaded = controls.find('.mejs-time-loaded'),
current = controls.find('.mejs-time-current'),
handle = controls.find('.mejs-time-handle'),
timefloat = controls.find('.mejs-time-float'),
timefloatcurrent = controls.find('.mejs-time-float-current'),
handleMouseMove = function (e) {
// mouse position relative to the object
var x = e.pageX,
offset = total.offset(),
width = total.outerWidth(),
percentage = 0,
newTime = 0,
pos = x - offset.left;
if (x > offset.left && x <= width + offset.left && media.duration) {
percentage = ((x - offset.left) / width);
newTime = (percentage <= 0.02) ? 0 : percentage * media.duration;
// seek to where the mouse is
if (mouseIsDown) {
media.setCurrentTime(newTime);
}
// position floating time box
if (!mejs.MediaFeatures.hasTouch) {
timefloat.css('left', pos);
timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
timefloat.show();
}
}
},
mouseIsDown = false,
mouseIsOver = false;
// handle clicks
//controls.find('.mejs-time-rail').delegate('span', 'click', handleMouseMove);
total
.bind('mousedown', function (e) {
// only handle left clicks
if (e.which === 1) {
mouseIsDown = true;
handleMouseMove(e);
$(document)
.bind('mousemove.dur', function(e) {
handleMouseMove(e);
})
.bind('mouseup.dur', function (e) {
mouseIsDown = false;
timefloat.hide();
$(document).unbind('.dur');
});
return false;
}
})
.bind('mouseenter', function(e) {
mouseIsOver = true;
$(document).bind('mousemove.dur', function(e) {
handleMouseMove(e);
});
if (!mejs.MediaFeatures.hasTouch) {
timefloat.show();
}
})
.bind('mouseleave',function(e) {
mouseIsOver = false;
if (!mouseIsDown) {
$(document).unbind('.dur');
timefloat.hide();
}
});
// loading
media.addEventListener('progress', function (e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// current time
media.addEventListener('timeupdate', function(e) {
player.setProgressRail(e);
player.setCurrentRail(e);
}, false);
// store for later use
t.loaded = loaded;
t.total = total;
t.current = current;
t.handle = handle;
},
setProgressRail: function(e) {
var
t = this,
target = (e != undefined) ? e.target : t.media,
percent = null;
// newest HTML5 spec has buffered array (FF4, Webkit)
if (target && target.buffered && target.buffered.length > 0 && target.buffered.end && target.duration) {
// TODO: account for a real array with multiple values (only Firefox 4 has this so far)
percent = target.buffered.end(0) / target.duration;
}
// Some browsers (e.g., FF3.6 and Safari 5) cannot calculate target.bufferered.end()
// to be anything other than 0. If the byte count is available we use this instead.
// Browsers that support the else if do not seem to have the bufferedBytes value and
// should skip to there. Tested in Safari 5, Webkit head, FF3.6, Chrome 6, IE 7/8.
else if (target && target.bytesTotal != undefined && target.bytesTotal > 0 && target.bufferedBytes != undefined) {
percent = target.bufferedBytes / target.bytesTotal;
}
// Firefox 3 with an Ogg file seems to go this way
else if (e && e.lengthComputable && e.total != 0) {
percent = e.loaded/e.total;
}
// finally update the progress bar
if (percent !== null) {
percent = Math.min(1, Math.max(0, percent));
// update loaded bar
if (t.loaded && t.total) {
t.loaded.width(t.total.width() * percent);
}
}
},
setCurrentRail: function() {
var t = this;
if (t.media.currentTime != undefined && t.media.duration) {
// update bar and handle
if (t.total && t.handle) {
var
newWidth = t.total.width() * t.media.currentTime / t.media.duration,
handlePos = newWidth - (t.handle.outerWidth(true) / 2);
t.current.width(newWidth);
t.handle.css('left', handlePos);
}
}
}
});
})(mejs.$);
(function($) {
// options
$.extend(mejs.MepDefaults, {
duration: -1,
timeAndDurationSeparator: ' <span> | </span> '
});
// current and duration 00:00 / 00:00
$.extend(MediaElementPlayer.prototype, {
buildcurrent: function(player, controls, layers, media) {
var t = this;
$('<div class="mejs-time">'+
'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:' : '')
+ (player.options.showTimecodeFrameCount? '00:00:00':'00:00')+ '</span>'+
'</div>')
.appendTo(controls);
t.currenttime = t.controls.find('.mejs-currenttime');
media.addEventListener('timeupdate',function() {
player.updateCurrent();
}, false);
},
buildduration: function(player, controls, layers, media) {
var t = this;
if (controls.children().last().find('.mejs-currenttime').length > 0) {
$(t.options.timeAndDurationSeparator +
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>')
.appendTo(controls.find('.mejs-time'));
} else {
// add class to current time
controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
$('<div class="mejs-time mejs-duration-container">'+
'<span class="mejs-duration">' +
(t.options.duration > 0 ?
mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25) :
((player.options.alwaysShowHours ? '00:' : '') + (player.options.showTimecodeFrameCount? '00:00:00':'00:00'))
) +
'</span>' +
'</div>')
.appendTo(controls);
}
t.durationD = t.controls.find('.mejs-duration');
media.addEventListener('timeupdate',function() {
player.updateDuration();
}, false);
},
updateCurrent: function() {
var t = this;
if (t.currenttime) {
t.currenttime.html(mejs.Utility.secondsToTimeCode(t.media.currentTime, t.options.alwaysShowHours || t.media.duration > 3600, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
},
updateDuration: function() {
var t = this;
if (t.media.duration && t.durationD) {
t.durationD.html(mejs.Utility.secondsToTimeCode(t.media.duration, t.options.alwaysShowHours, t.options.showTimecodeFrameCount, t.options.framesPerSecond || 25));
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
muteText: 'Mute Toggle',
hideVolumeOnTouchDevices: true,
audioVolume: 'horizontal',
videoVolume: 'vertical'
});
$.extend(MediaElementPlayer.prototype, {
buildvolume: function(player, controls, layers, media) {
// Android and iOS don't support volume controls
if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
return;
var t = this,
mode = (t.isVideo) ? t.options.videoVolume : t.options.audioVolume,
mute = (mode == 'horizontal') ?
// horizontal version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'</div>' +
'<div class="mejs-horizontal-volume-slider">'+ // outer background
'<div class="mejs-horizontal-volume-total"></div>'+ // line background
'<div class="mejs-horizontal-volume-current"></div>'+ // current volume
'<div class="mejs-horizontal-volume-handle"></div>'+ // handle
'</div>'
)
.appendTo(controls) :
// vertical version
$('<div class="mejs-button mejs-volume-button mejs-mute">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '"></button>'+
'<div class="mejs-volume-slider">'+ // outer background
'<div class="mejs-volume-total"></div>'+ // line background
'<div class="mejs-volume-current"></div>'+ // current volume
'<div class="mejs-volume-handle"></div>'+ // handle
'</div>'+
'</div>')
.appendTo(controls),
volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),
positionVolumeHandle = function(volume, secondTry) {
if (!volumeSlider.is(':visible') && typeof secondTry != 'undefined') {
volumeSlider.show();
positionVolumeHandle(volume, true);
volumeSlider.hide()
return;
}
// correct to 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// ajust mute button style
if (volume == 0) {
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
// position slider
if (mode == 'vertical') {
var
// height of the full size volume slider background
totalHeight = volumeTotal.height(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new top position based on the current volume
// 70% volume on 100px height == top:30px
newTop = totalHeight - (totalHeight * volume);
// handle
volumeHandle.css('top', totalPosition.top + newTop - (volumeHandle.height() / 2));
// show the current visibility
volumeCurrent.height(totalHeight - newTop );
volumeCurrent.css('top', totalPosition.top + newTop);
} else {
var
// height of the full size volume slider background
totalWidth = volumeTotal.width(),
// top/left of full size volume slider background
totalPosition = volumeTotal.position(),
// the new left position based on the current volume
newLeft = totalWidth * volume;
// handle
volumeHandle.css('left', totalPosition.left + newLeft - (volumeHandle.width() / 2));
// rezize the current part of the volume bar
volumeCurrent.width( newLeft );
}
},
handleVolumeMove = function(e) {
var volume = null,
totalOffset = volumeTotal.offset();
// calculate the new volume based on the moust position
if (mode == 'vertical') {
var
railHeight = volumeTotal.height(),
totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
newY = e.pageY - totalOffset.top;
volume = (railHeight - newY) / railHeight;
// the controls just hide themselves (usually when mouse moves too far up)
if (totalOffset.top == 0 || totalOffset.left == 0)
return;
} else {
var
railWidth = volumeTotal.width(),
newX = e.pageX - totalOffset.left;
volume = newX / railWidth;
}
// ensure the volume isn't outside 0-1
volume = Math.max(0,volume);
volume = Math.min(volume,1);
// position the slider and handle
positionVolumeHandle(volume);
// set the media object (this will trigger the volumechanged event)
if (volume == 0) {
media.setMuted(true);
} else {
media.setMuted(false);
}
media.setVolume(volume);
},
mouseIsDown = false,
mouseIsOver = false;
// SLIDER
mute
.hover(function() {
volumeSlider.show();
mouseIsOver = true;
}, function() {
mouseIsOver = false;
if (!mouseIsDown && mode == 'vertical') {
volumeSlider.hide();
}
});
volumeSlider
.bind('mouseover', function() {
mouseIsOver = true;
})
.bind('mousedown', function (e) {
handleVolumeMove(e);
$(document)
.bind('mousemove.vol', function(e) {
handleVolumeMove(e);
})
.bind('mouseup.vol', function () {
mouseIsDown = false;
$(document).unbind('.vol');
if (!mouseIsOver && mode == 'vertical') {
volumeSlider.hide();
}
});
mouseIsDown = true;
return false;
});
// MUTE button
mute.find('button').click(function() {
media.setMuted( !media.muted );
});
// listen for volume change events from other sources
media.addEventListener('volumechange', function(e) {
if (!mouseIsDown) {
if (media.muted) {
positionVolumeHandle(0);
mute.removeClass('mejs-mute').addClass('mejs-unmute');
} else {
positionVolumeHandle(media.volume);
mute.removeClass('mejs-unmute').addClass('mejs-mute');
}
}
}, false);
if (t.container.is(':visible')) {
// set initial volume
positionVolumeHandle(player.options.startVolume);
// shim gets the startvolume as a parameter, but we have to set it on the native <video> and <audio> elements
if (media.pluginType === 'native') {
media.setVolume(player.options.startVolume);
}
}
}
});
})(mejs.$);
(function($) {
$.extend(mejs.MepDefaults, {
usePluginFullScreen: true,
newWindowCallback: function() { return '';},
fullscreenText: 'Fullscreen'
});
$.extend(MediaElementPlayer.prototype, {
isFullScreen: false,
isNativeFullScreen: false,
docStyleOverflow: null,
isInIframe: false,
buildfullscreen: function(player, controls, layers, media) {
if (!player.isVideo)
return;
player.isInIframe = (window.location != window.parent.location);
// native events
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
// chrome doesn't alays fire this in an iframe
player.container.bind(mejs.MediaFeatures.fullScreenEventName, function(e) {
//player.container.bind('webkitfullscreenchange', function(e) {
if (mejs.MediaFeatures.isFullScreen()) {
player.isNativeFullScreen = true;
// reset the controls once we are fully in full screen
player.setControlsSize();
} else {
player.isNativeFullScreen = false;
// when a user presses ESC
// make sure to put the player back into place
player.exitFullScreen();
}
});
}
var t = this,
normalHeight = 0,
normalWidth = 0,
container = player.container,
fullscreenBtn =
$('<div class="mejs-button mejs-fullscreen-button">' +
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '"></button>' +
'</div>')
.appendTo(controls);
if (t.media.pluginType === 'native' || (!t.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)) {
fullscreenBtn.click(function() {
var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;
if (isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
});
} else {
var hideTimeout = null,
supportsPointerEvents = (function() {
// TAKEN FROM MODERNIZR
var element = document.createElement('x'),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if(!('pointerEvents' in element.style)){
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild(element);
supports = getComputedStyle &&
getComputedStyle(element, '').pointerEvents === 'auto';
documentElement.removeChild(element);
return !!supports;
})();
console.log('supportsPointerEvents', supportsPointerEvents);
if (supportsPointerEvents && !mejs.MediaFeatures.isOpera) { // opera doesn't allow this :(
// allows clicking through the fullscreen button and controls down directly to Flash
/*
When a user puts his mouse over the fullscreen button, the controls are disabled
So we put a div over the video and another one on iether side of the fullscreen button
that caputre mouse movement
and restore the controls once the mouse moves outside of the fullscreen button
*/
var fullscreenIsDisabled = false,
restoreControls = function() {
if (fullscreenIsDisabled) {
// hide the hovers
videoHoverDiv.hide();
controlsLeftHoverDiv.hide();
controlsRightHoverDiv.hide();
// restore the control bar
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
// store for later
fullscreenIsDisabled = false;
}
},
videoHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsLeftHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
controlsRightHoverDiv = $('<div class="mejs-fullscreen-hover" />').appendTo(t.container).mouseover(restoreControls),
positionHoverDivs = function() {
var style = {position: 'absolute', top: 0, left: 0}; //, backgroundColor: '#f00'};
videoHoverDiv.css(style);
controlsLeftHoverDiv.css(style);
controlsRightHoverDiv.css(style);
// over video, but not controls
videoHoverDiv
.width( t.container.width() )
.height( t.container.height() - t.controls.height() );
// over controls, but not the fullscreen button
var fullScreenBtnOffset = fullscreenBtn.offset().left - t.container.offset().left;
fullScreenBtnWidth = fullscreenBtn.outerWidth(true);
controlsLeftHoverDiv
.width( fullScreenBtnOffset )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height()});
// after the fullscreen button
controlsRightHoverDiv
.width( t.container.width() - fullScreenBtnOffset - fullScreenBtnWidth )
.height( t.controls.height() )
.css({top: t.container.height() - t.controls.height(),
left: fullScreenBtnOffset + fullScreenBtnWidth});
};
$(document).resize(function() {
positionHoverDivs();
});
// on hover, kill the fullscreen button's HTML handling, allowing clicks down to Flash
fullscreenBtn
.mouseover(function() {
if (!t.isFullScreen) {
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
// move the button in Flash into place
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, false);
// allows click through
fullscreenBtn.css('pointer-events', 'none');
t.controls.css('pointer-events', 'none');
// show the divs that will restore things
videoHoverDiv.show();
controlsRightHoverDiv.show();
controlsLeftHoverDiv.show();
positionHoverDivs();
fullscreenIsDisabled = true;
}
});
// restore controls anytime the user enters or leaves fullscreen
media.addEventListener('fullscreenchange', function(e) {
restoreControls();
});
// the mouseout event doesn't work on the fullscren button, because we already killed the pointer-events
// so we use the document.mousemove event to restore controls when the mouse moves outside the fullscreen button
/*
$(document).mousemove(function(e) {
// if the mouse is anywhere but the fullsceen button, then restore it all
if (fullscreenIsDisabled) {
var fullscreenBtnPos = fullscreenBtn.offset();
if (e.pageY < fullscreenBtnPos.top || e.pageY > fullscreenBtnPos.top + fullscreenBtn.outerHeight(true) ||
e.pageX < fullscreenBtnPos.left || e.pageX > fullscreenBtnPos.left + fullscreenBtn.outerWidth(true)
) {
fullscreenBtn.css('pointer-events', '');
t.controls.css('pointer-events', '');
fullscreenIsDisabled = false;
}
}
});
*/
} else {
// the hover state will show the fullscreen button in Flash to hover up and click
fullscreenBtn
.mouseover(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
var buttonPos = fullscreenBtn.offset(),
containerPos = player.container.offset();
media.positionFullscreenButton(buttonPos.left - containerPos.left, buttonPos.top - containerPos.top, true);
})
.mouseout(function() {
if (hideTimeout !== null) {
clearTimeout(hideTimeout);
delete hideTimeout;
}
hideTimeout = setTimeout(function() {
media.hideFullscreenButton();
}, 1500);
});
}
}
player.fullscreenBtn = fullscreenBtn;
$(document).bind('keydown',function (e) {
if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
player.exitFullScreen();
}
});
},
enterFullScreen: function() {
var t = this;
// firefox+flash can't adjust plugin sizes without resetting :(
if (t.media.pluginType !== 'native' && (mejs.MediaFeatures.isFirefox || t.options.usePluginFullScreen)) {
//t.media.setFullscreen(true);
//player.isFullScreen = true;
return;
}
// store overflow
docStyleOverflow = document.documentElement.style.overflow;
// set it to not show scroll bars so 100% will work
document.documentElement.style.overflow = 'hidden';
// store sizing
normalHeight = t.container.height();
normalWidth = t.container.width();
// attempt to do true fullscreen (Safari 5.1 and Firefox Nightly only for now)
if (t.media.pluginType === 'native') {
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(t.container[0]);
//return;
if (t.isInIframe) {
// sometimes exiting from fullscreen doesn't work
// notably in Chrome <iframe>. Fixed in version 17
setTimeout(function checkFullscreen() {
if (t.isNativeFullScreen) {
// check if the video is suddenly not really fullscreen
if ($(window).width() !== screen.width) {
// manually exit
t.exitFullScreen();
} else {
// test again
setTimeout(checkFullscreen, 500);
}
}
}, 500);
}
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
t.media.webkitEnterFullscreen();
return;
}
}
// check for iframe launch
if (t.isInIframe) {
var url = t.options.newWindowCallback(this);
if (url !== '') {
// launch immediately
if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
return;
} else {
setTimeout(function() {
if (!t.isNativeFullScreen) {
t.pause();
window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
}
}, 250);
}
}
}
// full window code
// make full size
t.container
.addClass('mejs-container-fullscreen')
.width('100%')
.height('100%');
//.css({position: 'fixed', left: 0, top: 0, right: 0, bottom: 0, overflow: 'hidden', width: '100%', height: '100%', 'z-index': 1000});
// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
// Actually, it seems to be needed for IE8, too
//if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
setTimeout(function() {
t.container.css({width: '100%', height: '100%'});
t.setControlsSize();
}, 500);
//}
if (t.pluginType === 'native') {
t.$media
.width('100%')
.height('100%');
} else {
t.container.find('object, embed, iframe')
.width('100%')
.height('100%');
//if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
t.media.setVideoSize($(window).width(),$(window).height());
//}
}
t.layers.children('div')
.width('100%')
.height('100%');
if (t.fullscreenBtn) {
t.fullscreenBtn
.removeClass('mejs-fullscreen')
.addClass('mejs-unfullscreen');
}
t.setControlsSize();
t.isFullScreen = true;
},
exitFullScreen: function() {
var t = this;
// firefox can't adjust plugins
if (t.media.pluginType !== 'native' && mejs.MediaFeatures.isFirefox) {
t.media.setFullscreen(false);
//player.isFullScreen = false;
return;
}
// come outo of native fullscreen
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
mejs.MediaFeatures.cancelFullScreen();
}
// restore scroll bars to document
document.documentElement.style.overflow = docStyleOverflow;
t.container
.removeClass('mejs-container-fullscreen')
.width(normalWidth)
.height(normalHeight);
//.css({position: '', left: '', top: '', right: '', bottom: '', overflow: 'inherit', width: normalWidth + 'px', height: normalHeight + 'px', 'z-index': 1});
if (t.pluginType === 'native') {
t.$media
.width(normalWidth)
.height(normalHeight);
} else {
t.container.find('object embed')
.width(normalWidth)
.height(normalHeight);
t.media.setVideoSize(normalWidth, normalHeight);
}
t.layers.children('div')
.width(normalWidth)
.height(normalHeight);
t.fullscreenBtn
.removeClass('mejs-unfullscreen')
.addClass('mejs-fullscreen');
t.setControlsSize();
t.isFullScreen = false;
}
});
})(mejs.$);
(function($) {
// add extra default options
$.extend(mejs.MepDefaults, {
// this will automatically turn on a <track>
startLanguage: '',
tracksText: 'Captions/Subtitles'
});
$.extend(MediaElementPlayer.prototype, {
hasChapters: false,
buildtracks: function(player, controls, layers, media) {
if (!player.isVideo)
return;
if (player.tracks.length == 0)
return;
var t= this, i, options = '';
player.chapters =
$('<div class="mejs-chapters mejs-layer"></div>')
.prependTo(layers).hide();
player.captions =
$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position"><span class="mejs-captions-text"></span></div></div>')
.prependTo(layers).hide();
player.captionsText = player.captions.find('.mejs-captions-text');
player.captionsButton =
$('<div class="mejs-button mejs-captions-button">'+
'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '"></button>'+
'<div class="mejs-captions-selector">'+
'<ul>'+
'<li>'+
'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
'<label for="' + player.id + '_captions_none">None</label>'+
'</li>' +
'</ul>'+
'</div>'+
'</div>')
.appendTo(controls)
// hover
.hover(function() {
$(this).find('.mejs-captions-selector').css('visibility','visible');
}, function() {
$(this).find('.mejs-captions-selector').css('visibility','hidden');
})
// handle clicks to the language radio buttons
.delegate('input[type=radio]','click',function() {
lang = this.value;
if (lang == 'none') {
player.selectedTrack = null;
} else {
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].srclang == lang) {
player.selectedTrack = player.tracks[i];
player.captions.attr('lang', player.selectedTrack.srclang);
player.displayCaptions();
break;
}
}
}
});
//.bind('mouseenter', function() {
// player.captionsButton.find('.mejs-captions-selector').css('visibility','visible')
//});
if (!player.options.alwaysShowControls) {
// move with controls
player.container
.bind('mouseenter', function () {
// push captions above controls
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
})
.bind('mouseleave', function () {
if (!media.paused) {
// move back to normal place
player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
}
});
} else {
player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
}
player.trackToLoad = -1;
player.selectedTrack = null;
player.isLoadingTrack = false;
// add to list
for (i=0; i<player.tracks.length; i++) {
if (player.tracks[i].kind == 'subtitles') {
player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
}
}
player.loadNextTrack();
media.addEventListener('timeupdate',function(e) {
player.displayCaptions();
}, false);
media.addEventListener('loadedmetadata', function(e) {
player.displayChapters();
}, false);
player.container.hover(
function () {
// chapters
if (player.hasChapters) {
player.chapters.css('visibility','visible');
player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
}
},
function () {
if (player.hasChapters && !media.paused) {
player.chapters.fadeOut(200, function() {
$(this).css('visibility','hidden');
$(this).css('display','block');
});
}
});
// check for autoplay
if (player.node.getAttribute('autoplay') !== null) {
player.chapters.css('visibility','hidden');
}
},
loadNextTrack: function() {
var t = this;
t.trackToLoad++;
if (t.trackToLoad < t.tracks.length) {
t.isLoadingTrack = true;
t.loadTrack(t.trackToLoad);
} else {
// add done?
t.isLoadingTrack = false;
}
},
loadTrack: function(index){
var
t = this,
track = t.tracks[index],
after = function() {
track.isLoaded = true;
// create button
//t.addTrackButton(track.srclang);
t.enableTrackButton(track.srclang, track.label);
t.loadNextTrack();
};
if (track.isTranslation) {
// translate the first track
mejs.TrackFormatParser.translateTrackText(t.tracks[0].entries, t.tracks[0].srclang, track.srclang, t.options.googleApiKey, function(newOne) {
// store the new translation
track.entries = newOne;
after();
});
} else {
$.ajax({
url: track.src,
success: function(d) {
// parse the loaded file
track.entries = mejs.TrackFormatParser.parse(d);
after();
if (track.kind == 'chapters' && t.media.duration > 0) {
t.drawChapters(track);
}
},
error: function() {
t.loadNextTrack();
}
});
}
},
enableTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton
.find('input[value=' + lang + ']')
.prop('disabled',false)
.siblings('label')
.html( label );
// auto select
if (t.options.startLanguage == lang) {
$('#' + t.id + '_captions_' + lang).click();
}
t.adjustLanguageBox();
},
addTrackButton: function(lang, label) {
var t = this;
if (label === '') {
label = mejs.language.codes[lang] || lang;
}
t.captionsButton.find('ul').append(
$('<li>'+
'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
'</li>')
);
t.adjustLanguageBox();
// remove this from the dropdownlist (if it exists)
t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
},
adjustLanguageBox:function() {
var t = this;
// adjust the size of the outer box
t.captionsButton.find('.mejs-captions-selector').height(
t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
);
},
displayCaptions: function() {
if (typeof this.tracks == 'undefined')
return;
var
t = this,
i,
track = t.selectedTrack;
if (track != null && track.isLoaded) {
for (i=0; i<track.entries.times.length; i++) {
if (t.media.currentTime >= track.entries.times[i].start && t.media.currentTime <= track.entries.times[i].stop){
t.captionsText.html(track.entries.text[i]);
t.captions.show().height(0);
return; // exit out if one is visible;
}
}
t.captions.hide();
} else {
t.captions.hide();
}
},
displayChapters: function() {
var
t = this,
i;
for (i=0; i<t.tracks.length; i++) {
if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
t.drawChapters(t.tracks[i]);
t.hasChapters = true;
break;
}
}
},
drawChapters: function(chapters) {
var
t = this,
i,
dur,
//width,
//left,
percent = 0,
usedPercent = 0;
t.chapters.empty();
for (i=0; i<chapters.entries.times.length; i++) {
dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
percent = Math.floor(dur / t.media.duration * 100);
if (percent + usedPercent > 100 || // too large
i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
{
percent = 100 - usedPercent;
}
//width = Math.floor(t.width * dur / t.media.duration);
//left = Math.floor(t.width * chapters.entries.times[i].start / t.media.duration);
//if (left + width > t.width) {
// width = t.width - left;
//}
t.chapters.append( $(
'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' +
'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' +
'<span class="ch-title">' + chapters.entries.text[i] + '</span>' +
'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '–' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' +
'</div>' +
'</div>'));
usedPercent += percent;
}
t.chapters.find('div.mejs-chapter').click(function() {
t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
if (t.media.paused) {
t.media.play();
}
});
t.chapters.show();
}
});
mejs.language = {
codes: {
af:'Afrikaans',
sq:'Albanian',
ar:'Arabic',
be:'Belarusian',
bg:'Bulgarian',
ca:'Catalan',
zh:'Chinese',
'zh-cn':'Chinese Simplified',
'zh-tw':'Chinese Traditional',
hr:'Croatian',
cs:'Czech',
da:'Danish',
nl:'Dutch',
en:'English',
et:'Estonian',
tl:'Filipino',
fi:'Finnish',
fr:'French',
gl:'Galician',
de:'German',
el:'Greek',
ht:'Haitian Creole',
iw:'Hebrew',
hi:'Hindi',
hu:'Hungarian',
is:'Icelandic',
id:'Indonesian',
ga:'Irish',
it:'Italian',
ja:'Japanese',
ko:'Korean',
lv:'Latvian',
lt:'Lithuanian',
mk:'Macedonian',
ms:'Malay',
mt:'Maltese',
no:'Norwegian',
fa:'Persian',
pl:'Polish',
pt:'Portuguese',
//'pt-pt':'Portuguese (Portugal)',
ro:'Romanian',
ru:'Russian',
sr:'Serbian',
sk:'Slovak',
sl:'Slovenian',
es:'Spanish',
sw:'Swahili',
sv:'Swedish',
tl:'Tagalog',
th:'Thai',
tr:'Turkish',
uk:'Ukrainian',
vi:'Vietnamese',
cy:'Welsh',
yi:'Yiddish'
}
};
/*
Parses WebVVT format which should be formatted as
================================
WEBVTT
1
00:00:01,1 --> 00:00:05,000
A line of text
2
00:01:15,1 --> 00:02:05,000
A second line of text
===============================
Adapted from: http://www.delphiki.com/html5/playr
*/
mejs.TrackFormatParser = {
// match start "chapter-" (or anythingelse)
pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
split2: function (text, regex) {
// normal version for compliant browsers
// see below for IE fix
return text.split(regex);
},
parse: function(trackText) {
var
i = 0,
lines = this.split2(trackText, /\r?\n/),
entries = {text:[], times:[]},
timecode,
text;
for(; i<lines.length; i++) {
// check for the line number
if (this.pattern_identifier.exec(lines[i])){
// skip to the next line where the start --> end time code should be
i++;
timecode = this.pattern_timecode.exec(lines[i]);
if (timecode && i<lines.length){
i++;
// grab all the (possibly multi-line) text that follows
text = lines[i];
i++;
while(lines[i] !== '' && i<lines.length){
text = text + '\n' + lines[i];
i++;
}
// Text is in a different array so I can use .join
entries.text.push(text);
entries.times.push(
{
start: mejs.Utility.timeCodeToSeconds(timecode[1]),
stop: mejs.Utility.timeCodeToSeconds(timecode[3]),
settings: timecode[5]
});
}
}
}
return entries;
}
};
// test for browsers with bad String.split method.
if ('x\n\ny'.split(/\n/gi).length != 3) {
// add super slow IE8 and below version
mejs.TrackFormatParser.split2 = function(text, regex) {
var
parts = [],
chunk = '',
i;
for (i=0; i<text.length; i++) {
chunk += text.substring(i,i+1);
if (regex.test(chunk)) {
parts.push(chunk.replace(regex, ''));
chunk = '';
}
}
parts.push(chunk);
return parts;
}
}
})(mejs.$);
/*
* ContextMenu Plugin
*
*
*/
(function($) {
$.extend(mejs.MepDefaults,
{ 'contextMenuItems': [
// demo of a fullscreen option
{
render: function(player) {
// check for fullscreen plugin
if (typeof player.enterFullScreen == 'undefined')
return null;
if (player.isFullScreen) {
return "Turn off Fullscreen";
} else {
return "Go Fullscreen";
}
},
click: function(player) {
if (player.isFullScreen) {
player.exitFullScreen();
} else {
player.enterFullScreen();
}
}
}
,
// demo of a mute/unmute button
{
render: function(player) {
if (player.media.muted) {
return "Unmute";
} else {
return "Mute";
}
},
click: function(player) {
if (player.media.muted) {
player.setMuted(false);
} else {
player.setMuted(true);
}
}
},
// separator
{
isSeparator: true
}
,
// demo of simple download video
{
render: function(player) {
return "Download Video";
},
click: function(player) {
window.location.href = player.media.currentSrc;
}
}
]}
);
$.extend(MediaElementPlayer.prototype, {
buildcontextmenu: function(player, controls, layers, media) {
// create context menu
player.contextMenu = $('<div class="mejs-contextmenu"></div>')
.appendTo($('body'))
.hide();
// create events for showing context menu
player.container.bind('contextmenu', function(e) {
if (player.isContextMenuEnabled) {
e.preventDefault();
player.renderContextMenu(e.clientX-1, e.clientY-1);
return false;
}
});
player.container.bind('click', function() {
player.contextMenu.hide();
});
player.contextMenu.bind('mouseleave', function() {
//console.log('context hover out');
player.startContextMenuTimer();
});
},
isContextMenuEnabled: true,
enableContextMenu: function() {
this.isContextMenuEnabled = true;
},
disableContextMenu: function() {
this.isContextMenuEnabled = false;
},
contextMenuTimeout: null,
startContextMenuTimer: function() {
//console.log('startContextMenuTimer');
var t = this;
t.killContextMenuTimer();
t.contextMenuTimer = setTimeout(function() {
t.hideContextMenu();
t.killContextMenuTimer();
}, 750);
},
killContextMenuTimer: function() {
var timer = this.contextMenuTimer;
//console.log('killContextMenuTimer', timer);
if (timer != null) {
clearTimeout(timer);
delete timer;
timer = null;
}
},
hideContextMenu: function() {
this.contextMenu.hide();
},
renderContextMenu: function(x,y) {
// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
var t = this,
html = '',
items = t.options.contextMenuItems;
for (var i=0, il=items.length; i<il; i++) {
if (items[i].isSeparator) {
html += '<div class="mejs-contextmenu-separator"></div>';
} else {
var rendered = items[i].render(t);
// render can return null if the item doesn't need to be used at the moment
if (rendered != null) {
html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
}
}
}
// position and show the context menu
t.contextMenu
.empty()
.append($(html))
.css({top:y, left:x})
.show();
// bind events
t.contextMenu.find('.mejs-contextmenu-item').each(function() {
// which one is this?
var $dom = $(this),
itemIndex = parseInt( $dom.data('itemindex'), 10 ),
item = t.options.contextMenuItems[itemIndex];
// bind extra functionality?
if (typeof item.show != 'undefined')
item.show( $dom , t);
// bind click action
$dom.click(function() {
// perform click action
if (typeof item.click != 'undefined')
item.click(t);
// close
t.contextMenu.hide();
});
});
// stop the controls from hiding
setTimeout(function() {
t.killControlsTimer('rev3');
}, 100);
}
});
})(mejs.$);
| jozefizso/cdnjs | ajax/libs/mediaelement/2.9.0/mediaelement-and-player.js | JavaScript | mit | 121,166 |
YUI.add('test', function(Y) {
/**
* YUI JavaScript Testing Framework
*
* @module test
*/
Y.namespace("Test");
/**
* Test case containing various tests to run.
* @param template An object containing any number of test methods, other methods,
* an optional name, and anything else the test case needs.
* @class Case
* @namespace Test
* @constructor
*/
Y.Test.Case = function (template) {
/**
* Special rules for the test case. Possible subobjects
* are fail, for tests that should fail, and error, for
* tests that should throw an error.
*
* @property _should
* @type Object
* @protected
*/
this._should = {};
//copy over all properties from the template to this object
for (var prop in template) {
this[prop] = template[prop];
}
//check for a valid name
if (!Y.Lang.isString(this.name)){
/**
* Name for the test case.
*
* @property name
* @type String
*/
this.name = "testCase" + Y.guid();
}
};
Y.Test.Case.prototype = {
/**
* Resumes a paused test and runs the given function.
* @param {Function} segment (Optional) The function to run.
* If omitted, the test automatically passes.
* @return {Void}
* @method resume
*/
resume : function (segment) {
Y.Test.Runner.resume(segment);
},
/**
* Causes the test case to wait a specified amount of time and then
* continue executing the given code.
* @param {Function} segment (Optional) The function to run after the delay.
* If omitted, the TestRunner will wait until resume() is called.
* @param {int} delay (Optional) The number of milliseconds to wait before running
* the function. If omitted, defaults to zero.
* @return {Void}
* @method wait
*/
wait : function (segment, delay){
var args = arguments;
if (Y.Lang.isFunction(args[0])){
throw new Y.Test.Wait(args[0], args[1]);
} else {
throw new Y.Test.Wait(function(){
Y.Assert.fail("Timeout: wait() called but resume() never called.");
}, (Y.Lang.isNumber(args[0]) ? args[0] : 10000));
}
},
//-------------------------------------------------------------------------
// Stub Methods
//-------------------------------------------------------------------------
/**
* Function to run before each test is executed.
* @return {Void}
* @method setUp
*/
setUp : function () {
},
/**
* Function to run after each test is executed.
* @return {Void}
* @method tearDown
*/
tearDown: function () {
}
};
/**
* Represents a stoppage in test execution to wait for an amount of time before
* continuing.
* @param {Function} segment A function to run when the wait is over.
* @param {int} delay The number of milliseconds to wait before running the code.
* @class Wait
* @namespace Test
* @constructor
*
*/
Y.Test.Wait = function (segment, delay) {
/**
* The segment of code to run when the wait is over.
* @type Function
* @property segment
*/
this.segment = (Y.Lang.isFunction(segment) ? segment : null);
/**
* The delay before running the segment of code.
* @type int
* @property delay
*/
this.delay = (Y.Lang.isNumber(delay) ? delay : 0);
};
Y.namespace("Test");
/**
* A test suite that can contain a collection of TestCase and TestSuite objects.
* @param {String|Object} data The name of the test suite or an object containing
* a name property as well as setUp and tearDown methods.
* @namespace Test
* @class Suite
* @constructor
*/
Y.Test.Suite = function (data /*:String||Object*/) {
/**
* The name of the test suite.
* @type String
* @property name
*/
this.name = "";
/**
* Array of test suites and
* @property items
* @type Array
* @private
*/
this.items = [];
//initialize the properties
if (Y.Lang.isString(data)){
this.name = data;
} else if (Y.Lang.isObject(data)){
Y.mix(this, data, true);
}
//double-check name
if (this.name === ""){
this.name = "testSuite" + Y.guid();
}
};
Y.Test.Suite.prototype = {
/**
* Adds a test suite or test case to the test suite.
* @param {Test.Suite|Test.Case} testObject The test suite or test case to add.
* @return {Void}
* @method add
*/
add : function (testObject /*:Y.Test.Suite*/) {
if (testObject instanceof Y.Test.Suite || testObject instanceof Y.Test.Case) {
this.items.push(testObject);
}
return this;
},
//-------------------------------------------------------------------------
// Stub Methods
//-------------------------------------------------------------------------
/**
* Function to run before each test is executed.
* @return {Void}
* @method setUp
*/
setUp : function () {
},
/**
* Function to run after each test is executed.
* @return {Void}
* @method tearDown
*/
tearDown: function () {
}
};
/*
* Runs test suites and test cases, providing events to allowing for the
* interpretation of test results.
* @namespace Test
* @class Runner
* @static
*/
Y.Test.Runner = (function(){
/* (intentionally not documented)
* A node in the test tree structure. May represent a TestSuite, TestCase, or
* test function.
* @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
* @class TestNode
* @constructor
* @private
*/
function TestNode(testObject){
/* (intentionally not documented)
* The TestSuite, TestCase, or test function represented by this node.
* @type Variant
* @property testObject
*/
this.testObject = testObject;
/* (intentionally not documented)
* Pointer to this node's first child.
* @type TestNode
* @property firstChild
*/
this.firstChild = null;
/* (intentionally not documented)
* Pointer to this node's last child.
* @type TestNode
* @property lastChild
*/
this.lastChild = null;
/* (intentionally not documented)
* Pointer to this node's parent.
* @type TestNode
* @property parent
*/
this.parent = null;
/* (intentionally not documented)
* Pointer to this node's next sibling.
* @type TestNode
* @property next
*/
this.next = null;
/* (intentionally not documented)
* Test results for this test object.
* @type object
* @property results
*/
this.results = {
passed : 0,
failed : 0,
total : 0,
ignored : 0,
duration: 0
};
//initialize results
if (testObject instanceof Y.Test.Suite){
this.results.type = "testsuite";
this.results.name = testObject.name;
} else if (testObject instanceof Y.Test.Case){
this.results.type = "testcase";
this.results.name = testObject.name;
}
}
TestNode.prototype = {
/* (intentionally not documented)
* Appends a new test object (TestSuite, TestCase, or test function name) as a child
* of this node.
* @param {Variant} testObject A TestSuite, TestCase, or the name of a test function.
* @return {Void}
*/
appendChild : function (testObject){
var node = new TestNode(testObject);
if (this.firstChild === null){
this.firstChild = this.lastChild = node;
} else {
this.lastChild.next = node;
this.lastChild = node;
}
node.parent = this;
return node;
}
};
/**
* Runs test suites and test cases, providing events to allowing for the
* interpretation of test results.
* @namespace Test
* @class Runner
* @static
*/
function TestRunner(){
//inherit from EventProvider
TestRunner.superclass.constructor.apply(this,arguments);
/**
* Suite on which to attach all TestSuites and TestCases to be run.
* @type Y.Test.Suite
* @property masterSuite
* @static
* @private
*/
this.masterSuite /*:Y.Test.Suite*/ = new Y.Test.Suite("yuitests" + (new Date()).getTime());
/**
* Pointer to the current node in the test tree.
* @type TestNode
* @private
* @property _cur
* @static
*/
this._cur = null;
/**
* Pointer to the root node in the test tree.
* @type TestNode
* @private
* @property _root
* @static
*/
this._root = null;
/**
* Indicates if the TestRunner will log events or not.
* @type Boolean
* @property _log
* @private
* @static
*/
this._log = true;
/**
* Indicates if the TestRunner is waiting as a result of
* wait() being called.
* @type Boolean
* @property _waiting
* @private
* @static
*/
this._waiting = false;
/**
* Indicates if the TestRunner is currently running tests.
* @type Boolean
* @private
* @property _running
* @static
*/
this._running = false;
/**
* Holds copy of the results object generated when all tests are
* complete.
* @type Object
* @private
* @property _lastResults
* @static
*/
this._lastResults = null;
//create events
var events = [
this.TEST_CASE_BEGIN_EVENT,
this.TEST_CASE_COMPLETE_EVENT,
this.TEST_SUITE_BEGIN_EVENT,
this.TEST_SUITE_COMPLETE_EVENT,
this.TEST_PASS_EVENT,
this.TEST_FAIL_EVENT,
this.TEST_IGNORE_EVENT,
this.COMPLETE_EVENT,
this.BEGIN_EVENT
];
for (var i=0; i < events.length; i++){
this.on(events[i], this._logEvent, this, true);
}
}
Y.extend(TestRunner, Y.Event.Target, {
//-------------------------------------------------------------------------
// Constants
//-------------------------------------------------------------------------
/**
* Fires when a test case is opened but before the first
* test is executed.
* @event testcasebegin
* @static
*/
TEST_CASE_BEGIN_EVENT : "testcasebegin",
/**
* Fires when all tests in a test case have been executed.
* @event testcasecomplete
* @static
*/
TEST_CASE_COMPLETE_EVENT : "testcasecomplete",
/**
* Fires when a test suite is opened but before the first
* test is executed.
* @event testsuitebegin
* @static
*/
TEST_SUITE_BEGIN_EVENT : "testsuitebegin",
/**
* Fires when all test cases in a test suite have been
* completed.
* @event testsuitecomplete
* @static
*/
TEST_SUITE_COMPLETE_EVENT : "testsuitecomplete",
/**
* Fires when a test has passed.
* @event pass
* @static
*/
TEST_PASS_EVENT : "pass",
/**
* Fires when a test has failed.
* @event fail
* @static
*/
TEST_FAIL_EVENT : "fail",
/**
* Fires when a test has been ignored.
* @event ignore
* @static
*/
TEST_IGNORE_EVENT : "ignore",
/**
* Fires when all test suites and test cases have been completed.
* @event complete
* @static
*/
COMPLETE_EVENT : "complete",
/**
* Fires when the run() method is called.
* @event begin
* @static
*/
BEGIN_EVENT : "begin",
//-------------------------------------------------------------------------
// Logging-Related Methods
//-------------------------------------------------------------------------
/**
* Disable logging via Y.log(). Test output will not be visible unless
* TestRunner events are subscribed to.
* @return {Void}
* @method disableLogging
* @static
*/
disableLogging: function(){
this._log = false;
},
/**
* Enable logging via Y.log(). Test output is published and can be read via
* logreader.
* @return {Void}
* @method enableLogging
* @static
*/
enableLogging: function(){
this._log = true;
},
/**
* Logs TestRunner events using Y.log().
* @param {Object} event The event object for the event.
* @return {Void}
* @method _logEvent
* @private
* @static
*/
_logEvent: function(event){
//data variables
var message = "";
var messageType = "";
switch(event.type){
case this.BEGIN_EVENT:
message = "Testing began at " + (new Date()).toString() + ".";
messageType = "info";
break;
case this.COMPLETE_EVENT:
message = Y.substitute("Testing completed at " +
(new Date()).toString() + ".\n" +
"Passed:{passed} Failed:{failed} " +
"Total:{total} ({ignored} ignored)",
event.results);
messageType = "info";
break;
case this.TEST_FAIL_EVENT:
message = event.testName + ": failed.\n" + event.error.getMessage();
messageType = "fail";
break;
case this.TEST_IGNORE_EVENT:
message = event.testName + ": ignored.";
messageType = "ignore";
break;
case this.TEST_PASS_EVENT:
message = event.testName + ": passed.";
messageType = "pass";
break;
case this.TEST_SUITE_BEGIN_EVENT:
message = "Test suite \"" + event.testSuite.name + "\" started.";
messageType = "info";
break;
case this.TEST_SUITE_COMPLETE_EVENT:
message = Y.substitute("Test suite \"" +
event.testSuite.name + "\" completed" + ".\n" +
"Passed:{passed} Failed:{failed} " +
"Total:{total} ({ignored} ignored)",
event.results);
messageType = "info";
break;
case this.TEST_CASE_BEGIN_EVENT:
message = "Test case \"" + event.testCase.name + "\" started.";
messageType = "info";
break;
case this.TEST_CASE_COMPLETE_EVENT:
message = Y.substitute("Test case \"" +
event.testCase.name + "\" completed.\n" +
"Passed:{passed} Failed:{failed} " +
"Total:{total} ({ignored} ignored)",
event.results);
messageType = "info";
break;
default:
message = "Unexpected event " + event.type;
message = "info";
}
//only log if required
if (this._log){
Y.log(message, messageType, "TestRunner");
}
},
//-------------------------------------------------------------------------
// Test Tree-Related Methods
//-------------------------------------------------------------------------
/**
* Adds a test case to the test tree as a child of the specified node.
* @param {TestNode} parentNode The node to add the test case to as a child.
* @param {Test.Case} testCase The test case to add.
* @return {Void}
* @static
* @private
* @method _addTestCaseToTestTree
*/
_addTestCaseToTestTree : function (parentNode, testCase /*:Y.Test.Case*/){
//add the test suite
var node = parentNode.appendChild(testCase),
prop,
testName;
//iterate over the items in the test case
for (prop in testCase){
if ((prop.indexOf("test") === 0 || (prop.toLowerCase().indexOf("should") > -1 && prop.indexOf(" ") > -1 ))&& Y.Lang.isFunction(testCase[prop])){
node.appendChild(prop);
}
}
},
/**
* Adds a test suite to the test tree as a child of the specified node.
* @param {TestNode} parentNode The node to add the test suite to as a child.
* @param {Test.Suite} testSuite The test suite to add.
* @return {Void}
* @static
* @private
* @method _addTestSuiteToTestTree
*/
_addTestSuiteToTestTree : function (parentNode, testSuite /*:Y.Test.Suite*/) {
//add the test suite
var node = parentNode.appendChild(testSuite);
//iterate over the items in the master suite
for (var i=0; i < testSuite.items.length; i++){
if (testSuite.items[i] instanceof Y.Test.Suite) {
this._addTestSuiteToTestTree(node, testSuite.items[i]);
} else if (testSuite.items[i] instanceof Y.Test.Case) {
this._addTestCaseToTestTree(node, testSuite.items[i]);
}
}
},
/**
* Builds the test tree based on items in the master suite. The tree is a hierarchical
* representation of the test suites, test cases, and test functions. The resulting tree
* is stored in _root and the pointer _cur is set to the root initially.
* @return {Void}
* @static
* @private
* @method _buildTestTree
*/
_buildTestTree : function () {
this._root = new TestNode(this.masterSuite);
//this._cur = this._root;
//iterate over the items in the master suite
for (var i=0; i < this.masterSuite.items.length; i++){
if (this.masterSuite.items[i] instanceof Y.Test.Suite) {
this._addTestSuiteToTestTree(this._root, this.masterSuite.items[i]);
} else if (this.masterSuite.items[i] instanceof Y.Test.Case) {
this._addTestCaseToTestTree(this._root, this.masterSuite.items[i]);
}
}
},
//-------------------------------------------------------------------------
// Private Methods
//-------------------------------------------------------------------------
/**
* Handles the completion of a test object's tests. Tallies test results
* from one level up to the next.
* @param {TestNode} node The TestNode representing the test object.
* @return {Void}
* @method _handleTestObjectComplete
* @private
*/
_handleTestObjectComplete : function (node) {
if (Y.Lang.isObject(node.testObject)){
if (node.parent){
node.parent.results.passed += node.results.passed;
node.parent.results.failed += node.results.failed;
node.parent.results.total += node.results.total;
node.parent.results.ignored += node.results.ignored;
//node.parent.results.duration += node.results.duration;
node.parent.results[node.testObject.name] = node.results;
}
if (node.testObject instanceof Y.Test.Suite){
node.testObject.tearDown();
node.results.duration = (new Date()) - node._start;
this.fire(this.TEST_SUITE_COMPLETE_EVENT, { testSuite: node.testObject, results: node.results});
} else if (node.testObject instanceof Y.Test.Case){
node.results.duration = (new Date()) - node._start;
this.fire(this.TEST_CASE_COMPLETE_EVENT, { testCase: node.testObject, results: node.results});
}
}
},
//-------------------------------------------------------------------------
// Navigation Methods
//-------------------------------------------------------------------------
/**
* Retrieves the next node in the test tree.
* @return {TestNode} The next node in the test tree or null if the end is reached.
* @private
* @static
* @method _next
*/
_next : function () {
if (this._cur === null){
this._cur = this._root;
} else if (this._cur.firstChild) {
this._cur = this._cur.firstChild;
} else if (this._cur.next) {
this._cur = this._cur.next;
} else {
while (this._cur && !this._cur.next && this._cur !== this._root){
this._handleTestObjectComplete(this._cur);
this._cur = this._cur.parent;
}
this._handleTestObjectComplete(this._cur);
if (this._cur == this._root){
this._cur.results.type = "report";
this._cur.results.timestamp = (new Date()).toLocaleString();
this._cur.results.duration = (new Date()) - this._cur._start;
this._lastResults = this._cur.results;
this._running = false;
this.fire(this.COMPLETE_EVENT, { results: this._lastResults});
this._cur = null;
} else {
this._cur = this._cur.next;
}
}
return this._cur;
},
/**
* Runs a test case or test suite, returning the results.
* @param {Test.Case|Test.Suite} testObject The test case or test suite to run.
* @return {Object} Results of the execution with properties passed, failed, and total.
* @private
* @method _run
* @static
*/
_run : function () {
//flag to indicate if the TestRunner should wait before continuing
var shouldWait = false;
//get the next test node
var node = this._next();
if (node !== null) {
//set flag to say the testrunner is running
this._running = true;
//eliminate last results
this._lastResult = null;
var testObject = node.testObject;
//figure out what to do
if (Y.Lang.isObject(testObject)){
if (testObject instanceof Y.Test.Suite){
this.fire(this.TEST_SUITE_BEGIN_EVENT, { testSuite: testObject });
node._start = new Date();
testObject.setUp();
} else if (testObject instanceof Y.Test.Case){
this.fire(this.TEST_CASE_BEGIN_EVENT, { testCase: testObject });
node._start = new Date();
}
//some environments don't support setTimeout
if (typeof setTimeout != "undefined"){
setTimeout(function(){
Y.Test.Runner._run();
}, 0);
} else {
this._run();
}
} else {
this._runTest(node);
}
}
},
_resumeTest : function (segment) {
//get relevant information
var node = this._cur;
//we know there's no more waiting now
this._waiting = false;
//if there's no node, it probably means a wait() was called after resume()
if (!node){
//TODO: Handle in some way?
//console.log("wait() called after resume()");
//this.fire("error", { testCase: "(unknown)", test: "(unknown)", error: new Error("wait() called after resume()")} );
return;
}
var testName = node.testObject;
var testCase /*:Y.Test.Case*/ = node.parent.testObject;
//cancel other waits if available
if (testCase.__yui_wait){
clearTimeout(testCase.__yui_wait);
delete testCase.__yui_wait;
}
//get the "should" test cases
var shouldFail = (testCase._should.fail || {})[testName];
var shouldError = (testCase._should.error || {})[testName];
//variable to hold whether or not the test failed
var failed = false;
var error = null;
//try the test
try {
//run the test
segment.apply(testCase);
//if it should fail, and it got here, then it's a fail because it didn't
if (shouldFail){
error = new Y.Assert.ShouldFail();
failed = true;
} else if (shouldError){
error = new Y.Assert.ShouldError();
failed = true;
}
} catch (thrown){
//cancel any pending waits, the test already failed
if (testCase.__yui_wait){
clearTimeout(testCase.__yui_wait);
delete testCase.__yui_wait;
}
//figure out what type of error it was
if (thrown instanceof Y.Assert.Error) {
if (!shouldFail){
error = thrown;
failed = true;
}
} else if (thrown instanceof Y.Test.Wait){
if (Y.Lang.isFunction(thrown.segment)){
if (Y.Lang.isNumber(thrown.delay)){
//some environments don't support setTimeout
if (typeof setTimeout != "undefined"){
testCase.__yui_wait = setTimeout(function(){
Y.Test.Runner._resumeTest(thrown.segment);
}, thrown.delay);
this._waiting = true;
} else {
throw new Error("Asynchronous tests not supported in this environment.");
}
}
}
return;
} else {
//first check to see if it should error
if (!shouldError) {
error = new Y.Assert.UnexpectedError(thrown);
failed = true;
} else {
//check to see what type of data we have
if (Y.Lang.isString(shouldError)){
//if it's a string, check the error message
if (thrown.message != shouldError){
error = new Y.Assert.UnexpectedError(thrown);
failed = true;
}
} else if (Y.Lang.isFunction(shouldError)){
//if it's a function, see if the error is an instance of it
if (!(thrown instanceof shouldError)){
error = new Y.Assert.UnexpectedError(thrown);
failed = true;
}
} else if (Y.Lang.isObject(shouldError)){
//if it's an object, check the instance and message
if (!(thrown instanceof shouldError.constructor) ||
thrown.message != shouldError.message){
error = new Y.Assert.UnexpectedError(thrown);
failed = true;
}
}
}
}
}
//fire appropriate event
if (failed) {
this.fire(this.TEST_FAIL_EVENT, { testCase: testCase, testName: testName, error: error });
} else {
this.fire(this.TEST_PASS_EVENT, { testCase: testCase, testName: testName });
}
//run the tear down
testCase.tearDown();
//calculate duration
var duration = (new Date()) - node._start;
//update results
node.parent.results[testName] = {
result: failed ? "fail" : "pass",
message: error ? error.getMessage() : "Test passed",
type: "test",
name: testName,
duration: duration
};
if (failed){
node.parent.results.failed++;
} else {
node.parent.results.passed++;
}
node.parent.results.total++;
//set timeout not supported in all environments
if (typeof setTimeout != "undefined"){
setTimeout(function(){
Y.Test.Runner._run();
}, 0);
} else {
this._run();
}
},
/**
* Handles an error as if it occurred within the currently executing
* test. This is for mock methods that may be called asynchronously
* and therefore out of the scope of the TestRunner. Previously, this
* error would bubble up to the browser. Now, this method is used
* to tell TestRunner about the error. This should never be called
* by anyplace other than the Mock object.
* @param {Error} error The error object.
* @return {Void}
* @method _handleError
* @private
* @static
*/
_handleError: function(error){
if (this._waiting){
this._resumeTest(function(){
throw error;
});
} else {
throw error;
}
},
/**
* Runs a single test based on the data provided in the node.
* @param {TestNode} node The TestNode representing the test to run.
* @return {Void}
* @static
* @private
* @method _runTest
*/
_runTest : function (node) {
//get relevant information
var testName = node.testObject;
var testCase /*:Y.Test.Case*/ = node.parent.testObject;
var test = testCase[testName];
//get the "should" test cases
var shouldIgnore = (testCase._should.ignore || {})[testName];
//figure out if the test should be ignored or not
if (shouldIgnore){
//update results
node.parent.results[testName] = {
result: "ignore",
message: "Test ignored",
type: "test",
name: testName
};
node.parent.results.ignored++;
node.parent.results.total++;
this.fire(this.TEST_IGNORE_EVENT, { testCase: testCase, testName: testName });
//some environments don't support setTimeout
if (typeof setTimeout != "undefined"){
setTimeout(function(){
Y.Test.Runner._run();
}, 0);
} else {
this._run();
}
} else {
//mark the start time
node._start = new Date();
//run the setup
testCase.setUp();
//now call the body of the test
this._resumeTest(test);
}
},
//-------------------------------------------------------------------------
// Misc Methods
//-------------------------------------------------------------------------
/**
* Retrieves the name of the current result set.
* @return {String} The name of the result set.
* @method getName
*/
getName: function(){
return this.masterSuite.name;
},
/**
* The name assigned to the master suite of the TestRunner. This is the name
* that is output as the root's name when results are retrieved.
* @param {String} name The name of the result set.
* @return {Void}
* @method setName
*/
setName: function(name){
this.masterSuite.name = name;
},
//-------------------------------------------------------------------------
// Protected Methods
//-------------------------------------------------------------------------
/*
* Fires events for the TestRunner. This overrides the default fire()
* method from EventProvider to add the type property to the data that is
* passed through on each event call.
* @param {String} type The type of event to fire.
* @param {Object} data (Optional) Data for the event.
* @method fire
* @static
* @protected
*/
fire : function (type, data) {
data = data || {};
data.type = type;
TestRunner.superclass.fire.call(this, type, data);
},
//-------------------------------------------------------------------------
// Public Methods
//-------------------------------------------------------------------------
/**
* Adds a test suite or test case to the list of test objects to run.
* @param testObject Either a TestCase or a TestSuite that should be run.
* @return {Void}
* @method add
* @static
*/
add : function (testObject) {
this.masterSuite.add(testObject);
return this;
},
/**
* Removes all test objects from the runner.
* @return {Void}
* @method clear
* @static
*/
clear : function () {
this.masterSuite = new Y.Test.Suite("yuitests" + (new Date()).getTime());
},
/**
* Indicates if the TestRunner is waiting for a test to resume
* @return {Boolean} True if the TestRunner is waiting, false if not.
* @method isWaiting
* @static
*/
isWaiting: function() {
return this._waiting;
},
/**
* Indicates that the TestRunner is busy running tests and therefore can't
* be stopped and results cannot be gathered.
* @return {Boolean} True if the TestRunner is running, false if not.
* @method isRunning
*/
isRunning: function(){
return this._running;
},
/**
* Returns the last complete results set from the TestRunner. Null is returned
* if the TestRunner is running or no tests have been run.
* @param {Function} format (Optional) A test format to return the results in.
* @return {Object|String} Either the results object or, if a test format is
* passed as the argument, a string representing the results in a specific
* format.
* @method getResults
*/
getResults: function(format){
if (!this._running && this._lastResults){
if (Y.Lang.isFunction(format)){
return format(this._lastResults);
} else {
return this._lastResults;
}
} else {
return null;
}
},
/**
* Returns the coverage report for the files that have been executed.
* This returns only coverage information for files that have been
* instrumented using YUI Test Coverage and only those that were run
* in the same pass.
* @param {Function} format (Optional) A coverage format to return results in.
* @return {Object|String} Either the coverage object or, if a coverage
* format is specified, a string representing the results in that format.
* @method getCoverage
*/
getCoverage: function(format){
if (!this._running && typeof _yuitest_coverage == "object"){
if (Y.Lang.isFunction(format)){
return format(_yuitest_coverage);
} else {
return _yuitest_coverage;
}
} else {
return null;
}
},
/**
* Resumes the TestRunner after wait() was called.
* @param {Function} segment The function to run as the rest
* of the haulted test.
* @return {Void}
* @method resume
* @static
*/
resume : function (segment) {
if (Y.Test.Runner._waiting){
this._resumeTest(segment || function(){});
} else {
throw new Error("resume() called without wait().");
}
},
/**
* Runs the test suite.
* @param {Boolean} oldMode (Optional) Specifies that the <= 2.8 way of
* internally managing test suites should be used.
* @return {Void}
* @method run
* @static
*/
run : function (oldMode) {
//pointer to runner to avoid scope issues
var runner = Y.Test.Runner;
//if there's only one suite on the masterSuite, move it up
if (!oldMode && this.masterSuite.items.length == 1 && this.masterSuite.items[0] instanceof Y.Test.Suite){
this.masterSuite = this.masterSuite.items[0];
}
//build the test tree
runner._buildTestTree();
//set when the test started
runner._root._start = new Date();
//fire the begin event
runner.fire(runner.BEGIN_EVENT);
//begin the testing
runner._run();
}
});
return new TestRunner();
})();
/**
* @module test
*/
/**
* The Assert object provides functions to test JavaScript values against
* known and expected results. Whenever a comparison (assertion) fails,
* an error is thrown.
*
* @class Assert
* @static
*/
Y.Assert = {
/**
* The number of assertions performed.
* @property _asserts
* @type int
* @private
*/
_asserts: 0,
//-------------------------------------------------------------------------
// Helper Methods
//-------------------------------------------------------------------------
/**
* Formats a message so that it can contain the original assertion message
* in addition to the custom message.
* @param {String} customMessage The message passed in by the developer.
* @param {String} defaultMessage The message created by the error by default.
* @return {String} The final error message, containing either or both.
* @protected
* @static
* @method _formatMessage
*/
_formatMessage : function (customMessage, defaultMessage) {
var message = customMessage;
if (Y.Lang.isString(customMessage) && customMessage.length > 0){
return Y.Lang.substitute(customMessage, { message: defaultMessage });
} else {
return defaultMessage;
}
},
/**
* Returns the number of assertions that have been performed.
* @method _getCount
* @protected
* @static
*/
_getCount: function(){
return this._asserts;
},
/**
* Increments the number of assertions that have been performed.
* @method _increment
* @protected
* @static
*/
_increment: function(){
this._asserts++;
},
/**
* Resets the number of assertions that have been performed to 0.
* @method _reset
* @protected
* @static
*/
_reset: function(){
this._asserts = 0;
},
//-------------------------------------------------------------------------
// Generic Assertion Methods
//-------------------------------------------------------------------------
/**
* Forces an assertion error to occur.
* @param {String} message (Optional) The message to display with the failure.
* @method fail
* @static
*/
fail : function (message) {
throw new Y.Assert.Error(Y.Assert._formatMessage(message, "Test force-failed."));
},
//-------------------------------------------------------------------------
// Equality Assertion Methods
//-------------------------------------------------------------------------
/**
* Asserts that a value is equal to another. This uses the double equals sign
* so type cohersion may occur.
* @param {Object} expected The expected value.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method areEqual
* @static
*/
areEqual : function (expected, actual, message) {
Y.Assert._increment();
if (expected != actual) {
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be equal."), expected, actual);
}
},
/**
* Asserts that a value is not equal to another. This uses the double equals sign
* so type cohersion may occur.
* @param {Object} unexpected The unexpected value.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method areNotEqual
* @static
*/
areNotEqual : function (unexpected, actual,
message) {
Y.Assert._increment();
if (unexpected == actual) {
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be equal."), unexpected);
}
},
/**
* Asserts that a value is not the same as another. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} unexpected The unexpected value.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method areNotSame
* @static
*/
areNotSame : function (unexpected, actual, message) {
Y.Assert._increment();
if (unexpected === actual) {
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be the same."), unexpected);
}
},
/**
* Asserts that a value is the same as another. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} expected The expected value.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method areSame
* @static
*/
areSame : function (expected, actual, message) {
Y.Assert._increment();
if (expected !== actual) {
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be the same."), expected, actual);
}
},
//-------------------------------------------------------------------------
// Boolean Assertion Methods
//-------------------------------------------------------------------------
/**
* Asserts that a value is false. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isFalse
* @static
*/
isFalse : function (actual, message) {
Y.Assert._increment();
if (false !== actual) {
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be false."), false, actual);
}
},
/**
* Asserts that a value is true. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isTrue
* @static
*/
isTrue : function (actual, message) {
Y.Assert._increment();
if (true !== actual) {
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be true."), true, actual);
}
},
//-------------------------------------------------------------------------
// Special Value Assertion Methods
//-------------------------------------------------------------------------
/**
* Asserts that a value is not a number.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isNaN
* @static
*/
isNaN : function (actual, message){
Y.Assert._increment();
if (!isNaN(actual)){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be NaN."), NaN, actual);
}
},
/**
* Asserts that a value is not the special NaN value.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isNotNaN
* @static
*/
isNotNaN : function (actual, message){
Y.Assert._increment();
if (isNaN(actual)){
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be NaN."), NaN);
}
},
/**
* Asserts that a value is not null. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isNotNull
* @static
*/
isNotNull : function (actual, message) {
Y.Assert._increment();
if (Y.Lang.isNull(actual)) {
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Values should not be null."), null);
}
},
/**
* Asserts that a value is not undefined. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isNotUndefined
* @static
*/
isNotUndefined : function (actual, message) {
Y.Assert._increment();
if (Y.Lang.isUndefined(actual)) {
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should not be undefined."), undefined);
}
},
/**
* Asserts that a value is null. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isNull
* @static
*/
isNull : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isNull(actual)) {
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be null."), null, actual);
}
},
/**
* Asserts that a value is undefined. This uses the triple equals sign
* so no type cohersion may occur.
* @param {Object} actual The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isUndefined
* @static
*/
isUndefined : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isUndefined(actual)) {
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be undefined."), undefined, actual);
}
},
//--------------------------------------------------------------------------
// Instance Assertion Methods
//--------------------------------------------------------------------------
/**
* Asserts that a value is an array.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isArray
* @static
*/
isArray : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isArray(actual)){
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be an array."), actual);
}
},
/**
* Asserts that a value is a Boolean.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isBoolean
* @static
*/
isBoolean : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isBoolean(actual)){
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a Boolean."), actual);
}
},
/**
* Asserts that a value is a function.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isFunction
* @static
*/
isFunction : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isFunction(actual)){
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a function."), actual);
}
},
/**
* Asserts that a value is an instance of a particular object. This may return
* incorrect results when comparing objects from one frame to constructors in
* another frame. For best results, don't use in a cross-frame manner.
* @param {Function} expected The function that the object should be an instance of.
* @param {Object} actual The object to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isInstanceOf
* @static
*/
isInstanceOf : function (expected, actual, message) {
Y.Assert._increment();
if (!(actual instanceof expected)){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value isn't an instance of expected type."), expected, actual);
}
},
/**
* Asserts that a value is a number.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isNumber
* @static
*/
isNumber : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isNumber(actual)){
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a number."), actual);
}
},
/**
* Asserts that a value is an object.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isObject
* @static
*/
isObject : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isObject(actual)){
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be an object."), actual);
}
},
/**
* Asserts that a value is a string.
* @param {Object} actual The value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isString
* @static
*/
isString : function (actual, message) {
Y.Assert._increment();
if (!Y.Lang.isString(actual)){
throw new Y.Assert.UnexpectedValue(Y.Assert._formatMessage(message, "Value should be a string."), actual);
}
},
/**
* Asserts that a value is of a particular type.
* @param {String} expectedType The expected type of the variable.
* @param {Object} actualValue The actual value to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isTypeOf
* @static
*/
isTypeOf : function (expectedType, actualValue, message){
Y.Assert._increment();
if (typeof actualValue != expectedType){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Value should be of type " + expectedType + "."), expected, typeof actualValue);
}
}
};
/**
* Asserts that a given condition is true. If not, then a Y.Assert.Error object is thrown
* and the test fails.
* @method assert
* @param {Boolean} condition The condition to test.
* @param {String} message The message to display if the assertion fails.
* @for YUI
* @static
*/
Y.assert = function(condition, message){
Y.Assert._increment();
if (!condition){
throw new Y.Assert.Error(Y.Assert._formatMessage(message, "Assertion failed."));
}
};
/**
* Forces an assertion error to occur. Shortcut for Y.Assert.fail().
* @method fail
* @param {String} message (Optional) The message to display with the failure.
* @for YUI
* @static
*/
Y.fail = Y.Assert.fail;
//-----------------------------------------------------------------------------
// Assertion errors
//-----------------------------------------------------------------------------
/**
* Error is thrown whenever an assertion fails. It provides methods
* to more easily get at error information and also provides a base class
* from which more specific assertion errors can be derived.
*
* @param {String} message The message to display when the error occurs.
* @class Assert.Error
* @constructor
*/
Y.Assert.Error = function (message){
//call superclass
arguments.callee.superclass.constructor.call(this, message);
/*
* Error message. Must be duplicated to ensure browser receives it.
* @type String
* @property message
*/
this.message = message;
/**
* The name of the error that occurred.
* @type String
* @property name
*/
this.name = "Assert Error";
};
//inherit methods
Y.extend(Y.Assert.Error, Error, {
/**
* Returns a fully formatted error for an assertion failure. This should
* be overridden by all subclasses to provide specific information.
* @method getMessage
* @return {String} A string describing the error.
*/
getMessage : function () {
return this.message;
},
/**
* Returns a string representation of the error.
* @method toString
* @return {String} A string representation of the error.
*/
toString : function () {
return this.name + ": " + this.getMessage();
},
/**
* Returns a primitive value version of the error. Same as toString().
* @method valueOf
* @return {String} A primitive value version of the error.
*/
valueOf : function () {
return this.toString();
}
});
/**
* ComparisonFailure is subclass of Error that is thrown whenever
* a comparison between two values fails. It provides mechanisms to retrieve
* both the expected and actual value.
*
* @param {String} message The message to display when the error occurs.
* @param {Object} expected The expected value.
* @param {Object} actual The actual value that caused the assertion to fail.
* @extends Assert.Error
* @class Assert.ComparisonFailure
* @constructor
*/
Y.Assert.ComparisonFailure = function (message, expected, actual){
//call superclass
arguments.callee.superclass.constructor.call(this, message);
/**
* The expected value.
* @type Object
* @property expected
*/
this.expected = expected;
/**
* The actual value.
* @type Object
* @property actual
*/
this.actual = actual;
/**
* The name of the error that occurred.
* @type String
* @property name
*/
this.name = "ComparisonFailure";
};
//inherit methods
Y.extend(Y.Assert.ComparisonFailure, Y.Assert.Error, {
/**
* Returns a fully formatted error for an assertion failure. This message
* provides information about the expected and actual values.
* @method toString
* @return {String} A string describing the error.
*/
getMessage : function () {
return this.message + "\nExpected: " + this.expected + " (" + (typeof this.expected) + ")" +
"\nActual: " + this.actual + " (" + (typeof this.actual) + ")";
}
});
/**
* UnexpectedValue is subclass of Error that is thrown whenever
* a value was unexpected in its scope. This typically means that a test
* was performed to determine that a value was *not* equal to a certain
* value.
*
* @param {String} message The message to display when the error occurs.
* @param {Object} unexpected The unexpected value.
* @extends Assert.Error
* @class Assert.UnexpectedValue
* @constructor
*/
Y.Assert.UnexpectedValue = function (message, unexpected){
//call superclass
arguments.callee.superclass.constructor.call(this, message);
/**
* The unexpected value.
* @type Object
* @property unexpected
*/
this.unexpected = unexpected;
/**
* The name of the error that occurred.
* @type String
* @property name
*/
this.name = "UnexpectedValue";
};
//inherit methods
Y.extend(Y.Assert.UnexpectedValue, Y.Assert.Error, {
/**
* Returns a fully formatted error for an assertion failure. The message
* contains information about the unexpected value that was encountered.
* @method getMessage
* @return {String} A string describing the error.
*/
getMessage : function () {
return this.message + "\nUnexpected: " + this.unexpected + " (" + (typeof this.unexpected) + ") ";
}
});
/**
* ShouldFail is subclass of Error that is thrown whenever
* a test was expected to fail but did not.
*
* @param {String} message The message to display when the error occurs.
* @extends Assert.Error
* @class Assert.ShouldFail
* @constructor
*/
Y.Assert.ShouldFail = function (message){
//call superclass
arguments.callee.superclass.constructor.call(this, message || "This test should fail but didn't.");
/**
* The name of the error that occurred.
* @type String
* @property name
*/
this.name = "ShouldFail";
};
//inherit methods
Y.extend(Y.Assert.ShouldFail, Y.Assert.Error);
/**
* ShouldError is subclass of Error that is thrown whenever
* a test is expected to throw an error but doesn't.
*
* @param {String} message The message to display when the error occurs.
* @extends Assert.Error
* @class Assert.ShouldError
* @constructor
*/
Y.Assert.ShouldError = function (message){
//call superclass
arguments.callee.superclass.constructor.call(this, message || "This test should have thrown an error but didn't.");
/**
* The name of the error that occurred.
* @type String
* @property name
*/
this.name = "ShouldError";
};
//inherit methods
Y.extend(Y.Assert.ShouldError, Y.Assert.Error);
/**
* UnexpectedError is subclass of Error that is thrown whenever
* an error occurs within the course of a test and the test was not expected
* to throw an error.
*
* @param {Error} cause The unexpected error that caused this error to be
* thrown.
* @extends Assert.Error
* @class Assert.UnexpectedError
* @constructor
*/
Y.Assert.UnexpectedError = function (cause){
//call superclass
arguments.callee.superclass.constructor.call(this, "Unexpected error: " + cause.message);
/**
* The unexpected error that occurred.
* @type Error
* @property cause
*/
this.cause = cause;
/**
* The name of the error that occurred.
* @type String
* @property name
*/
this.name = "UnexpectedError";
/**
* Stack information for the error (if provided).
* @type String
* @property stack
*/
this.stack = cause.stack;
};
//inherit methods
Y.extend(Y.Assert.UnexpectedError, Y.Assert.Error);
/**
* @module test
*/
/**
* The ArrayAssert object provides functions to test JavaScript array objects
* for a variety of cases.
*
* @class ArrayAssert
* @static
*/
Y.ArrayAssert = {
/**
* Asserts that a value is present in an array. This uses the triple equals
* sign so no type cohersion may occur.
* @param {Object} needle The value that is expected in the array.
* @param {Array} haystack An array of values.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method contains
* @static
*/
contains : function (needle, haystack,
message) {
Y.Assert._increment();
if (Y.Array.indexOf(haystack, needle) == -1){
Y.Assert.fail(Y.Assert._formatMessage(message, "Value " + needle + " (" + (typeof needle) + ") not found in array [" + haystack + "]."));
}
},
/**
* Asserts that a set of values are present in an array. This uses the triple equals
* sign so no type cohersion may occur. For this assertion to pass, all values must
* be found.
* @param {Object[]} needles An array of values that are expected in the array.
* @param {Array} haystack An array of values to check.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method containsItems
* @static
*/
containsItems : function (needles, haystack,
message) {
Y.Assert._increment();
//begin checking values
for (var i=0; i < needles.length; i++){
if (Y.Array.indexOf(haystack, needles[i]) == -1){
Y.Assert.fail(Y.Assert._formatMessage(message, "Value " + needles[i] + " (" + (typeof needles[i]) + ") not found in array [" + haystack + "]."));
}
}
},
/**
* Asserts that a value matching some condition is present in an array. This uses
* a function to determine a match.
* @param {Function} matcher A function that returns true if the items matches or false if not.
* @param {Array} haystack An array of values.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method containsMatch
* @static
*/
containsMatch : function (matcher, haystack,
message) {
Y.Assert._increment();
//check for valid matcher
if (typeof matcher != "function"){
throw new TypeError("ArrayAssert.containsMatch(): First argument must be a function.");
}
if (!Y.Array.some(haystack, matcher)){
Y.Assert.fail(Y.Assert._formatMessage(message, "No match found in array [" + haystack + "]."));
}
},
/**
* Asserts that a value is not present in an array. This uses the triple equals
* Asserts that a value is not present in an array. This uses the triple equals
* sign so no type cohersion may occur.
* @param {Object} needle The value that is expected in the array.
* @param {Array} haystack An array of values.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method doesNotContain
* @static
*/
doesNotContain : function (needle, haystack,
message) {
Y.Assert._increment();
if (Y.Array.indexOf(haystack, needle) > -1){
Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
}
},
/**
* Asserts that a set of values are not present in an array. This uses the triple equals
* sign so no type cohersion may occur. For this assertion to pass, all values must
* not be found.
* @param {Object[]} needles An array of values that are not expected in the array.
* @param {Array} haystack An array of values to check.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method doesNotContainItems
* @static
*/
doesNotContainItems : function (needles, haystack,
message) {
Y.Assert._increment();
for (var i=0; i < needles.length; i++){
if (Y.Array.indexOf(haystack, needles[i]) > -1){
Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
}
}
},
/**
* Asserts that no values matching a condition are present in an array. This uses
* a function to determine a match.
* @param {Function} matcher A function that returns true if the items matches or false if not.
* @param {Array} haystack An array of values.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method doesNotContainMatch
* @static
*/
doesNotContainMatch : function (matcher, haystack,
message) {
Y.Assert._increment();
//check for valid matcher
if (typeof matcher != "function"){
throw new TypeError("ArrayAssert.doesNotContainMatch(): First argument must be a function.");
}
if (Y.Array.some(haystack, matcher)){
Y.Assert.fail(Y.Assert._formatMessage(message, "Value found in array [" + haystack + "]."));
}
},
/**
* Asserts that the given value is contained in an array at the specified index.
* This uses the triple equals sign so no type cohersion will occur.
* @param {Object} needle The value to look for.
* @param {Array} haystack The array to search in.
* @param {int} index The index at which the value should exist.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method indexOf
* @static
*/
indexOf : function (needle, haystack, index, message) {
Y.Assert._increment();
//try to find the value in the array
for (var i=0; i < haystack.length; i++){
if (haystack[i] === needle){
if (index != i){
Y.Assert.fail(Y.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
}
return;
}
}
//if it makes it here, it wasn't found at all
Y.Assert.fail(Y.Assert._formatMessage(message, "Value doesn't exist in array [" + haystack + "]."));
},
/**
* Asserts that the values in an array are equal, and in the same position,
* as values in another array. This uses the double equals sign
* so type cohersion may occur. Note that the array objects themselves
* need not be the same for this test to pass.
* @param {Array} expected An array of the expected values.
* @param {Array} actual Any array of the actual values.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method itemsAreEqual
* @static
*/
itemsAreEqual : function (expected, actual,
message) {
Y.Assert._increment();
//first check array length
if (expected.length != actual.length){
Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
}
//begin checking values
for (var i=0; i < expected.length; i++){
if (expected[i] != actual[i]){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not equal."), expected[i], actual[i]);
}
}
},
/**
* Asserts that the values in an array are equivalent, and in the same position,
* as values in another array. This uses a function to determine if the values
* are equivalent. Note that the array objects themselves
* need not be the same for this test to pass.
* @param {Array} expected An array of the expected values.
* @param {Array} actual Any array of the actual values.
* @param {Function} comparator A function that returns true if the values are equivalent
* or false if not.
* @param {String} message (Optional) The message to display if the assertion fails.
* @return {Void}
* @method itemsAreEquivalent
* @static
*/
itemsAreEquivalent : function (expected, actual,
comparator, message) {
Y.Assert._increment();
//make sure the comparator is valid
if (typeof comparator != "function"){
throw new TypeError("ArrayAssert.itemsAreEquivalent(): Third argument must be a function.");
}
//first check array length
if (expected.length != actual.length){
Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
}
//begin checking values
for (var i=0; i < expected.length; i++){
if (!comparator(expected[i], actual[i])){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not equivalent."), expected[i], actual[i]);
}
}
},
/**
* Asserts that an array is empty.
* @param {Array} actual The array to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isEmpty
* @static
*/
isEmpty : function (actual, message) {
Y.Assert._increment();
if (actual.length > 0){
Y.Assert.fail(Y.Assert._formatMessage(message, "Array should be empty."));
}
},
/**
* Asserts that an array is not empty.
* @param {Array} actual The array to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method isNotEmpty
* @static
*/
isNotEmpty : function (actual, message) {
Y.Assert._increment();
if (actual.length === 0){
Y.Assert.fail(Y.Assert._formatMessage(message, "Array should not be empty."));
}
},
/**
* Asserts that the values in an array are the same, and in the same position,
* as values in another array. This uses the triple equals sign
* so no type cohersion will occur. Note that the array objects themselves
* need not be the same for this test to pass.
* @param {Array} expected An array of the expected values.
* @param {Array} actual Any array of the actual values.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method itemsAreSame
* @static
*/
itemsAreSame : function (expected, actual,
message) {
Y.Assert._increment();
//first check array length
if (expected.length != actual.length){
Y.Assert.fail(Y.Assert._formatMessage(message, "Array should have a length of " + expected.length + " but has a length of " + actual.length));
}
//begin checking values
for (var i=0; i < expected.length; i++){
if (expected[i] !== actual[i]){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values in position " + i + " are not the same."), expected[i], actual[i]);
}
}
},
/**
* Asserts that the given value is contained in an array at the specified index,
* starting from the back of the array.
* This uses the triple equals sign so no type cohersion will occur.
* @param {Object} needle The value to look for.
* @param {Array} haystack The array to search in.
* @param {int} index The index at which the value should exist.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method lastIndexOf
* @static
*/
lastIndexOf : function (needle, haystack, index, message) {
//try to find the value in the array
for (var i=haystack.length; i >= 0; i--){
if (haystack[i] === needle){
if (index != i){
Y.Assert.fail(Y.Assert._formatMessage(message, "Value exists at index " + i + " but should be at index " + index + "."));
}
return;
}
}
//if it makes it here, it wasn't found at all
Y.Assert.fail(Y.Assert._formatMessage(message, "Value doesn't exist in array."));
}
};
/**
* @module test
*/
/**
* The ObjectAssert object provides functions to test JavaScript objects
* for a variety of cases.
*
* @class ObjectAssert
* @static
*/
Y.ObjectAssert = {
areEqual: function(expected, actual, message) {
Y.Assert._increment();
Y.Object.each(expected, function(value, name){
if (expected[name] != actual[name]){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, "Values should be equal for property " + name), expected[name], actual[name]);
}
});
},
/**
* Asserts that an object has a property with the given name. The property may exist either
* on the object instance or in its prototype chain. The same as testing
* "property" in object.
* @param {String} propertyName The name of the property to test.
* @param {Object} object The object to search.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method hasKey
* @static
*/
hasKey: function (propertyName, object, message) {
Y.Assert._increment();
if (!(propertyName in object)){
Y.fail(Y.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object."));
}
},
/**
* Asserts that an object has all properties of a reference object. The properties may exist either
* on the object instance or in its prototype chain. The same as testing
* "property" in object.
* @param {Array} properties An array of property names that should be on the object.
* @param {Object} object The object to search.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method hasKeys
* @static
*/
hasKeys: function (properties, object, message) {
Y.Assert._increment();
for (var i=0; i < properties.length; i++){
if (!(properties[i] in object)){
Y.fail(Y.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object."));
}
}
},
/**
* Asserts that a property with the given name exists on an object instance (not on its prototype).
* @param {String} propertyName The name of the property to test.
* @param {Object} object The object to search.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method ownsKey
* @static
*/
ownsKey: function (propertyName, object, message) {
Y.Assert._increment();
if (!object.hasOwnProperty(propertyName)){
Y.fail(Y.Assert._formatMessage(message, "Property '" + propertyName + "' not found on object instance."));
}
},
/**
* Asserts that all properties exist on an object instance (not on its prototype).
* @param {Array} properties An array of property names that should be on the object.
* @param {Object} object The object to search.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method ownsKeys
* @static
*/
ownsKeys: function (properties, object, message) {
Y.Assert._increment();
for (var i=0; i < properties.length; i++){
if (!object.hasOwnProperty(properties[i])){
Y.fail(Y.Assert._formatMessage(message, "Property '" + properties[i] + "' not found on object instance."));
}
}
},
/**
* Asserts that an object owns no properties.
* @param {Object} object The object to check.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method ownsNoKeys
* @static
*/
ownsNoKeys : function (object, message) {
Y.Assert._increment();
var keys = Y.Object.keys(object);
if (keys.length > 0){
Y.fail(Y.Assert._formatMessage(message, "Object owns " + keys.length + " properties but should own none."));
}
}
};
/**
* @module test
*/
/**
* The DateAssert object provides functions to test JavaScript Date objects
* for a variety of cases.
*
* @class DateAssert
* @static
*/
Y.DateAssert = {
/**
* Asserts that a date's month, day, and year are equal to another date's.
* @param {Date} expected The expected date.
* @param {Date} actual The actual date to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method datesAreEqual
* @static
*/
datesAreEqual : function (expected, actual, message){
Y.Assert._increment();
if (expected instanceof Date && actual instanceof Date){
var msg = "";
//check years first
if (expected.getFullYear() != actual.getFullYear()){
msg = "Years should be equal.";
}
//now check months
if (expected.getMonth() != actual.getMonth()){
msg = "Months should be equal.";
}
//last, check the day of the month
if (expected.getDate() != actual.getDate()){
msg = "Days of month should be equal.";
}
if (msg.length){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, msg), expected, actual);
}
} else {
throw new TypeError("Y.Assert.datesAreEqual(): Expected and actual values must be Date objects.");
}
},
/**
* Asserts that a date's hour, minutes, and seconds are equal to another date's.
* @param {Date} expected The expected date.
* @param {Date} actual The actual date to test.
* @param {String} message (Optional) The message to display if the assertion fails.
* @method timesAreEqual
* @static
*/
timesAreEqual : function (expected, actual, message){
Y.Assert._increment();
if (expected instanceof Date && actual instanceof Date){
var msg = "";
//check hours first
if (expected.getHours() != actual.getHours()){
msg = "Hours should be equal.";
}
//now check minutes
if (expected.getMinutes() != actual.getMinutes()){
msg = "Minutes should be equal.";
}
//last, check the seconds
if (expected.getSeconds() != actual.getSeconds()){
msg = "Seconds should be equal.";
}
if (msg.length){
throw new Y.Assert.ComparisonFailure(Y.Assert._formatMessage(message, msg), expected, actual);
}
} else {
throw new TypeError("DateY.AsserttimesAreEqual(): Expected and actual values must be Date objects.");
}
}
};
Y.namespace("Test.Format");
/* (intentionally not documented)
* Basic XML escaping method. Replaces quotes, less-than, greater-than,
* apostrophe, and ampersand characters with their corresponding entities.
* @param {String} text The text to encode.
* @return {String} The XML-escaped text.
*/
function xmlEscape(text){
return text.replace(/[<>"'&]/g, function(value){
switch(value){
case "<": return "<";
case ">": return ">";
case "\"": return """;
case "'": return "'";
case "&": return "&";
}
});
}
/**
* Contains specific formatting options for test result information.
* @namespace Test
* @class Format
* @static
*/
/**
* Returns test results formatted as a JSON string. Requires JSON utility.
* @param {Object} result The results object created by TestRunner.
* @return {String} A JSON-formatted string of results.
* @method JSON
* @static
*/
Y.Test.Format.JSON = function(results) {
return Y.JSON.stringify(results);
};
/**
* Returns test results formatted as an XML string.
* @param {Object} result The results object created by TestRunner.
* @return {String} An XML-formatted string of results.
* @method XML
* @static
*/
Y.Test.Format.XML = function(results) {
function serializeToXML(results){
var l = Y.Lang,
xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";
if (l.isNumber(results.duration)){
xml += " duration=\"" + results.duration + "\"";
}
if (results.type == "test"){
xml += " result=\"" + results.result + "\" message=\"" + xmlEscape(results.message) + "\">";
} else {
xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
Y.Object.each(results, function(value){
if (l.isObject(value) && !l.isArray(value)){
xml += serializeToXML(value);
}
});
}
xml += "</" + results.type + ">";
return xml;
}
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToXML(results);
};
/**
* Returns test results formatted in JUnit XML format.
* @param {Object} result The results object created by TestRunner.
* @return {String} An XML-formatted string of results.
* @method JUnitXML
* @static
*/
Y.Test.Format.JUnitXML = function(results) {
function serializeToJUnitXML(results){
var l = Y.Lang,
xml = "";
switch (results.type){
//equivalent to testcase in JUnit
case "test":
if (results.result != "ignore"){
xml = "<testcase name=\"" + xmlEscape(results.name) + "\" time=\"" + (results.duration/1000) + "\">";
if (results.result == "fail"){
xml += "<failure message=\"" + xmlEscape(results.message) + "\"><![CDATA[" + results.message + "]]></failure>";
}
xml+= "</testcase>";
}
break;
//equivalent to testsuite in JUnit
case "testcase":
xml = "<testsuite name=\"" + xmlEscape(results.name) + "\" tests=\"" + results.total + "\" failures=\"" + results.failed + "\" time=\"" + (results.duration/1000) + "\">";
Y.Object.each(results, function(value){
if (l.isObject(value) && !l.isArray(value)){
xml += serializeToJUnitXML(value);
}
});
xml += "</testsuite>";
break;
//no JUnit equivalent, don't output anything
case "testsuite":
Y.Object.each(results, function(value){
if (l.isObject(value) && !l.isArray(value)){
xml += serializeToJUnitXML(value);
}
});
break;
//top-level, equivalent to testsuites in JUnit
case "report":
xml = "<testsuites>";
Y.Object.each(results, function(value){
if (l.isObject(value) && !l.isArray(value)){
xml += serializeToJUnitXML(value);
}
});
xml += "</testsuites>";
//no default
}
return xml;
}
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToJUnitXML(results);
};
/**
* Returns test results formatted in TAP format.
* For more information, see <a href="http://testanything.org/">Test Anything Protocol</a>.
* @param {Object} result The results object created by TestRunner.
* @return {String} A TAP-formatted string of results.
* @method TAP
* @static
*/
Y.Test.Format.TAP = function(results) {
var currentTestNum = 1;
function serializeToTAP(results){
var l = Y.Lang,
text = "";
switch (results.type){
case "test":
if (results.result != "ignore"){
text = "ok " + (currentTestNum++) + " - " + results.name;
if (results.result == "fail"){
text = "not " + text + " - " + results.message;
}
text += "\n";
} else {
text = "#Ignored test " + results.name + "\n";
}
break;
case "testcase":
text = "#Begin testcase " + results.name + "(" + results.failed + " failed of " + results.total + ")\n";
Y.Object.each(results, function(value){
if (l.isObject(value) && !l.isArray(value)){
text += serializeToTAP(value);
}
});
text += "#End testcase " + results.name + "\n";
break;
case "testsuite":
text = "#Begin testsuite " + results.name + "(" + results.failed + " failed of " + results.total + ")\n";
Y.Object.each(results, function(value){
if (l.isObject(value) && !l.isArray(value)){
text += serializeToTAP(value);
}
});
text += "#End testsuite " + results.name + "\n";
break;
case "report":
Y.Object.each(results, function(value){
if (l.isObject(value) && !l.isArray(value)){
text += serializeToTAP(value);
}
});
//no default
}
return text;
}
return "1.." + results.total + "\n" + serializeToTAP(results);
};
/**
* @module test
*/
Y.namespace("Coverage.Format");
/**
* Contains specific formatting options for coverage information.
* @class Coverage.Format
* @static
*/
/**
* Returns the coverage report in JSON format. This is the straight
* JSON representation of the native coverage report.
* @param {Object} coverage The coverage report object.
* @return {String} A JSON-formatted string of coverage data.
* @method JSON
* @static
*/
Y.Coverage.Format.JSON = function(coverage){
return Y.JSON.stringify(coverage);
};
/**
* Returns the coverage report in a JSON format compatible with
* Xdebug. See <a href="http://www.xdebug.com/docs/code_coverage">Xdebug Documentation</a>
* for more information. Note: function coverage is not available
* in this format.
* @param {Object} coverage The coverage report object.
* @return {String} A JSON-formatted string of coverage data.
* @method XdebugJSON
* @static
*/
Y.Coverage.Format.XdebugJSON = function(coverage){
var report = {};
Y.Object.each(coverage, function(value, name){
report[name] = coverage[name].lines;
});
return Y.JSON.stringify(report);
};
Y.namespace("Test");
/**
* An object capable of sending test results to a server.
* @param {String} url The URL to submit the results to.
* @param {Function} format (Optiona) A function that outputs the results in a specific format.
* Default is Y.Test.Format.XML.
* @constructor
* @namespace Test
* @class Reporter
*/
Y.Test.Reporter = function(url, format) {
/**
* The URL to submit the data to.
* @type String
* @property url
*/
this.url = url;
/**
* The formatting function to call when submitting the data.
* @type Function
* @property format
*/
this.format = format || Y.Test.Format.XML;
/**
* Extra fields to submit with the request.
* @type Object
* @property _fields
* @private
*/
this._fields = new Object();
/**
* The form element used to submit the results.
* @type HTMLFormElement
* @property _form
* @private
*/
this._form = null;
/**
* Iframe used as a target for form submission.
* @type HTMLIFrameElement
* @property _iframe
* @private
*/
this._iframe = null;
};
Y.Test.Reporter.prototype = {
//restore missing constructor
constructor: Y.Test.Reporter,
/**
* Adds a field to the form that submits the results.
* @param {String} name The name of the field.
* @param {Variant} value The value of the field.
* @return {Void}
* @method addField
*/
addField : function (name, value){
this._fields[name] = value;
},
/**
* Removes all previous defined fields.
* @return {Void}
* @method addField
*/
clearFields : function(){
this._fields = new Object();
},
/**
* Cleans up the memory associated with the TestReporter, removing DOM elements
* that were created.
* @return {Void}
* @method destroy
*/
destroy : function() {
if (this._form){
this._form.parentNode.removeChild(this._form);
this._form = null;
}
if (this._iframe){
this._iframe.parentNode.removeChild(this._iframe);
this._iframe = null;
}
this._fields = null;
},
/**
* Sends the report to the server.
* @param {Object} results The results object created by TestRunner.
* @return {Void}
* @method report
*/
report : function(results){
//if the form hasn't been created yet, create it
if (!this._form){
this._form = document.createElement("form");
this._form.method = "post";
this._form.style.visibility = "hidden";
this._form.style.position = "absolute";
this._form.style.top = 0;
document.body.appendChild(this._form);
// IE won't let you assign a name using the DOM, must do it the hacky way
var iframeContainer = document.createElement("div");
iframeContainer.innerHTML = "<iframe name=\"yuiTestTarget\"></iframe>";
this._iframe = iframeContainer.firstChild;
this._iframe.src = "javascript:false";
this._iframe.style.visibility = "hidden";
this._iframe.style.position = "absolute";
this._iframe.style.top = 0;
document.body.appendChild(this._iframe);
this._form.target = "yuiTestTarget";
}
//set the form's action
this._form.action = this.url;
//remove any existing fields
while(this._form.hasChildNodes()){
this._form.removeChild(this._form.lastChild);
}
//create default fields
this._fields.results = this.format(results);
this._fields.useragent = navigator.userAgent;
this._fields.timestamp = (new Date()).toLocaleString();
//add fields to the form
Y.Object.each(this._fields, function(value, prop){
if (typeof value != "function"){
var input = document.createElement("input");
input.type = "hidden";
input.name = prop;
input.value = value;
this._form.appendChild(input);
}
}, this);
//remove default fields
delete this._fields.results;
delete this._fields.useragent;
delete this._fields.timestamp;
if (arguments[1] !== false){
this._form.submit();
}
}
};
/**
* @module test
*/
/**
* Creates a new mock object.
* @class Mock
* @constructor
* @param {Object} template (Optional) An object whose methods
* should be stubbed out on the mock object. This object
* is used as the prototype of the mock object so instanceof
* works correctly.
*/
Y.Mock = function(template){
//use blank object is nothing is passed in
template = template || {};
var mock = null;
//try to create mock that keeps prototype chain intact
try {
mock = Y.Object(template);
} catch (ex) {
mock = {};
Y.log("Couldn't create mock with prototype.", "warn", "Mock");
}
//create new versions of the methods so that they don't actually do anything
Y.Object.each(template, function(name){
if (Y.Lang.isFunction(template[name])){
mock[name] = function(){
Y.Assert.fail("Method " + name + "() was called but was not expected to be.");
};
}
});
//return it
return mock;
};
/**
* Assigns an expectation to a mock object. This is used to create
* methods and properties on the mock object that are monitored for
* calls and changes, respectively.
* @param {Object} mock The object to add the expectation to.
* @param {Object} expectation An object defining the expectation. For
* a method, the keys "method" and "args" are required with
* an optional "returns" key available. For properties, the keys
* "property" and "value" are required.
* @return {void}
* @method expect
* @static
*/
Y.Mock.expect = function(mock /*:Object*/, expectation /*:Object*/){
//make sure there's a place to store the expectations
if (!mock.__expectations) {
mock.__expectations = {};
}
//method expectation
if (expectation.method){
var name = expectation.method,
args = expectation.args || expectation.arguments || [],
result = expectation.returns,
callCount = Y.Lang.isNumber(expectation.callCount) ? expectation.callCount : 1,
error = expectation.error,
run = expectation.run || function(){};
//save expectations
mock.__expectations[name] = expectation;
expectation.callCount = callCount;
expectation.actualCallCount = 0;
//process arguments
Y.Array.each(args, function(arg, i, array){
if (!(array[i] instanceof Y.Mock.Value)){
array[i] = Y.Mock.Value(Y.Assert.areSame, [arg], "Argument " + i + " of " + name + "() is incorrect.");
}
});
//if the method is expected to be called
if (callCount > 0){
mock[name] = function(){
try {
expectation.actualCallCount++;
Y.Assert.areEqual(args.length, arguments.length, "Method " + name + "() passed incorrect number of arguments.");
for (var i=0, len=args.length; i < len; i++){
//if (args[i]){
args[i].verify(arguments[i]);
//} else {
// Y.Assert.fail("Argument " + i + " (" + arguments[i] + ") was not expected to be used.");
//}
}
run.apply(this, arguments);
if (error){
throw error;
}
} catch (ex){
//route through TestRunner for proper handling
Y.Test.Runner._handleError(ex);
}
return result;
};
} else {
//method should fail if called when not expected
mock[name] = function(){
try {
Y.Assert.fail("Method " + name + "() should not have been called.");
} catch (ex){
//route through TestRunner for proper handling
Y.Test.Runner._handleError(ex);
}
};
}
} else if (expectation.property){
//save expectations
mock.__expectations[name] = expectation;
}
};
/**
* Verifies that all expectations of a mock object have been met and
* throws an assertion error if not.
* @param {Object} mock The object to verify..
* @return {void}
* @method verify
* @static
*/
Y.Mock.verify = function(mock /*:Object*/){
try {
Y.Object.each(mock.__expectations, function(expectation){
if (expectation.method) {
Y.Assert.areEqual(expectation.callCount, expectation.actualCallCount, "Method " + expectation.method + "() wasn't called the expected number of times.");
} else if (expectation.property){
Y.Assert.areEqual(expectation.value, mock[expectation.property], "Property " + expectation.property + " wasn't set to the correct value.");
}
});
} catch (ex){
//route through TestRunner for proper handling
Y.Test.Runner._handleError(ex);
}
};
/**
* Defines a custom mock validator for a particular argument.
* @class Mock.Value
* @param {Function} method The method to run on the argument. This should
* throw an assertion error if the value is invalid.
* @param {Array} originalArgs The first few arguments to pass in
* to the method. The value to test and failure message are
* always the last two arguments passed into method.
* @param {String} message The message to display if validation fails. If
* not specified, the default assertion error message is displayed.
* @return {void}
* @constructor Value
* @static
*/
Y.Mock.Value = function(method, originalArgs, message){
if (Y.instanceOf(this, Y.Mock.Value)){
this.verify = function(value){
var args = [].concat(originalArgs || []);
args.push(value);
args.push(message);
method.apply(null, args);
};
} else {
return new Y.Mock.Value(method, originalArgs, message);
}
};
/**
* Mock argument validator that accepts any value as valid.
* @property Any
* @type Function
* @static
*/
Y.Mock.Value.Any = Y.Mock.Value(function(){});
/**
* Mock argument validator that accepts only Boolean values as valid.
* @property Boolean
* @type Function
* @static
*/
Y.Mock.Value.Boolean = Y.Mock.Value(Y.Assert.isBoolean);
/**
* Mock argument validator that accepts only numeric values as valid.
* @property Number
* @type Function
* @static
*/
Y.Mock.Value.Number = Y.Mock.Value(Y.Assert.isNumber);
/**
* Mock argument validator that accepts only String values as valid.
* @property String
* @type Function
* @static
*/
Y.Mock.Value.String = Y.Mock.Value(Y.Assert.isString);
/**
* Mock argument validator that accepts only non-null objects values as valid.
* @property Object
* @type Function
* @static
*/
Y.Mock.Value.Object = Y.Mock.Value(Y.Assert.isObject);
/**
* Mock argument validator that accepts onlyfunctions as valid.
* @property Function
* @type Function
* @static
*/
Y.Mock.Value.Function = Y.Mock.Value(Y.Assert.isFunction);
/*Stub for future compatibility*/
if (typeof YUITest == "undefined" || !YUITest) {
YUITest = {
TestRunner: Y.Test.Runner,
ResultsFormat: Y.Test.Format,
TestFormat: Y.Test.Format,
CoverageFormat: Y.Coverage.Format
};
}
}, '@VERSION@' ,{requires:['event-simulate','event-custom','substitute','json-stringify']});
| tonytomov/cdnjs | ajax/libs/yui/3.5.0pr1/test/test-debug.js | JavaScript | mit | 117,340 |
(function(){if (!Date.now) Date.now = function() {
return +new Date;
};
try {
document.createElement("div").style.setProperty("opacity", 0, "");
} catch (error) {
var d3_style_prototype = CSSStyleDeclaration.prototype,
d3_style_setProperty = d3_style_prototype.setProperty;
d3_style_prototype.setProperty = function(name, value, priority) {
d3_style_setProperty.call(this, name, value + "", priority);
};
}
d3 = {version: "2.3.2"}; // semver
var d3_array = d3_arraySlice; // conversion for NodeLists
function d3_arrayCopy(pseudoarray) {
var i = -1, n = pseudoarray.length, array = [];
while (++i < n) array.push(pseudoarray[i]);
return array;
}
function d3_arraySlice(pseudoarray) {
return Array.prototype.slice.call(pseudoarray);
}
try {
d3_array(document.documentElement.childNodes)[0].nodeType;
} catch(e) {
d3_array = d3_arrayCopy;
}
var d3_arraySubclass = [].__proto__?
// Until ECMAScript supports array subclassing, prototype injection works well.
function(array, prototype) {
array.__proto__ = prototype;
}:
// And if your browser doesn't support __proto__, we'll use direct extension.
function(array, prototype) {
for (var property in prototype) array[property] = prototype[property];
};
function d3_this() {
return this;
}
d3.functor = function(v) {
return typeof v === "function" ? v : function() { return v; };
};
// A getter-setter method that preserves the appropriate `this` context.
d3.rebind = function(object, method) {
return function() {
var x = method.apply(object, arguments);
return arguments.length ? object : x;
};
};
d3.ascending = function(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
};
d3.descending = function(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
};
d3.min = function(array, f) {
var i = -1,
n = array.length,
a,
b;
if (arguments.length === 1) {
while (++i < n && ((a = array[i]) == null || a != a)) a = undefined;
while (++i < n) if ((b = array[i]) != null && a > b) a = b;
} else {
while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
}
return a;
};
d3.max = function(array, f) {
var i = -1,
n = array.length,
a,
b;
if (arguments.length === 1) {
while (++i < n && ((a = array[i]) == null || a != a)) a = undefined;
while (++i < n) if ((b = array[i]) != null && b > a) a = b;
} else {
while (++i < n && ((a = f.call(array, array[i], i)) == null || a != a)) a = undefined;
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
}
return a;
};
d3.sum = function(array, f) {
var s = 0,
n = array.length,
a,
i = -1;
if (arguments.length === 1) {
while (++i < n) if (!isNaN(a = +array[i])) s += a;
} else {
while (++i < n) if (!isNaN(a = +f.call(array, array[i], i))) s += a;
}
return s;
};
// R-7 per <http://en.wikipedia.org/wiki/Quantile>
d3.quantile = function(values, p) {
var H = (values.length - 1) * p + 1,
h = Math.floor(H),
v = values[h - 1],
e = H - h;
return e ? v + e * (values[h] - v) : v;
};
d3.zip = function() {
if (!(n = arguments.length)) return [];
for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m;) {
for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n;) {
zip[j] = arguments[j][i];
}
}
return zips;
};
function d3_zipLength(d) {
return d.length;
}
// Locate the insertion point for x in a to maintain sorted order. The
// arguments lo and hi may be used to specify a subset of the array which should
// be considered; by default the entire array is used. If x is already present
// in a, the insertion point will be before (to the left of) any existing
// entries. The return value is suitable for use as the first argument to
// `array.splice` assuming that a is already sorted.
//
// The returned insertion point i partitions the array a into two halves so that
// all v < x for v in a[lo:i] for the left side and all v >= x for v in a[i:hi]
// for the right side.
d3.bisectLeft = function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = (lo + hi) >> 1;
if (a[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
};
// Similar to bisectLeft, but returns an insertion point which comes after (to
// the right of) any existing entries of x in a.
//
// The returned insertion point i partitions the array into two halves so that
// all v <= x for v in a[lo:i] for the left side and all v > x for v in a[i:hi]
// for the right side.
d3.bisect =
d3.bisectRight = function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = (lo + hi) >> 1;
if (x < a[mid]) hi = mid;
else lo = mid + 1;
}
return lo;
};
d3.first = function(array, f) {
var i = 0,
n = array.length,
a = array[0],
b;
if (arguments.length === 1) f = d3.ascending;
while (++i < n) {
if (f.call(array, a, b = array[i]) > 0) {
a = b;
}
}
return a;
};
d3.last = function(array, f) {
var i = 0,
n = array.length,
a = array[0],
b;
if (arguments.length === 1) f = d3.ascending;
while (++i < n) {
if (f.call(array, a, b = array[i]) <= 0) {
a = b;
}
}
return a;
};
d3.nest = function() {
var nest = {},
keys = [],
sortKeys = [],
sortValues,
rollup;
function map(array, depth) {
if (depth >= keys.length) return rollup
? rollup.call(nest, array) : (sortValues
? array.sort(sortValues)
: array);
var i = -1,
n = array.length,
key = keys[depth++],
keyValue,
object,
o = {};
while (++i < n) {
if ((keyValue = key(object = array[i])) in o) {
o[keyValue].push(object);
} else {
o[keyValue] = [object];
}
}
for (keyValue in o) {
o[keyValue] = map(o[keyValue], depth);
}
return o;
}
function entries(map, depth) {
if (depth >= keys.length) return map;
var a = [],
sortKey = sortKeys[depth++],
key;
for (key in map) {
a.push({key: key, values: entries(map[key], depth)});
}
if (sortKey) a.sort(function(a, b) {
return sortKey(a.key, b.key);
});
return a;
}
nest.map = function(array) {
return map(array, 0);
};
nest.entries = function(array) {
return entries(map(array, 0), 0);
};
nest.key = function(d) {
keys.push(d);
return nest;
};
// Specifies the order for the most-recently specified key.
// Note: only applies to entries. Map keys are unordered!
nest.sortKeys = function(order) {
sortKeys[keys.length - 1] = order;
return nest;
};
// Specifies the order for leaf values.
// Applies to both maps and entries array.
nest.sortValues = function(order) {
sortValues = order;
return nest;
};
nest.rollup = function(f) {
rollup = f;
return nest;
};
return nest;
};
d3.keys = function(map) {
var keys = [];
for (var key in map) keys.push(key);
return keys;
};
d3.values = function(map) {
var values = [];
for (var key in map) values.push(map[key]);
return values;
};
d3.entries = function(map) {
var entries = [];
for (var key in map) entries.push({key: key, value: map[key]});
return entries;
};
d3.permute = function(array, indexes) {
var permutes = [],
i = -1,
n = indexes.length;
while (++i < n) permutes[i] = array[indexes[i]];
return permutes;
};
d3.merge = function(arrays) {
return Array.prototype.concat.apply([], arrays);
};
d3.split = function(array, f) {
var arrays = [],
values = [],
value,
i = -1,
n = array.length;
if (arguments.length < 2) f = d3_splitter;
while (++i < n) {
if (f.call(values, value = array[i], i)) {
values = [];
} else {
if (!values.length) arrays.push(values);
values.push(value);
}
}
return arrays;
};
function d3_splitter(d) {
return d == null;
}
function d3_collapse(s) {
return s.replace(/(^\s+)|(\s+$)/g, "").replace(/\s+/g, " ");
}
/**
* @param {number} start
* @param {number=} stop
* @param {number=} step
*/
d3.range = function(start, stop, step) {
if (arguments.length < 3) {
step = 1;
if (arguments.length < 2) {
stop = start;
start = 0;
}
}
if ((stop - start) / step == Infinity) throw new Error("infinite range");
var range = [],
i = -1,
j;
if (step < 0) while ((j = start + step * ++i) > stop) range.push(j);
else while ((j = start + step * ++i) < stop) range.push(j);
return range;
};
d3.requote = function(s) {
return s.replace(d3_requote_re, "\\$&");
};
var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
d3.round = function(x, n) {
return n
? Math.round(x * Math.pow(10, n)) * Math.pow(10, -n)
: Math.round(x);
};
d3.xhr = function(url, mime, callback) {
var req = new XMLHttpRequest;
if (arguments.length < 3) callback = mime;
else if (mime && req.overrideMimeType) req.overrideMimeType(mime);
req.open("GET", url, true);
req.onreadystatechange = function() {
if (req.readyState === 4) callback(req.status < 300 ? req : null);
};
req.send(null);
};
d3.text = function(url, mime, callback) {
function ready(req) {
callback(req && req.responseText);
}
if (arguments.length < 3) {
callback = mime;
mime = null;
}
d3.xhr(url, mime, ready);
};
d3.json = function(url, callback) {
d3.text(url, "application/json", function(text) {
callback(text ? JSON.parse(text) : null);
});
};
d3.html = function(url, callback) {
d3.text(url, "text/html", function(text) {
if (text != null) { // Treat empty string as valid HTML.
var range = document.createRange();
range.selectNode(document.body);
text = range.createContextualFragment(text);
}
callback(text);
});
};
d3.xml = function(url, mime, callback) {
function ready(req) {
callback(req && req.responseXML);
}
if (arguments.length < 3) {
callback = mime;
mime = null;
}
d3.xhr(url, mime, ready);
};
d3.ns = {
prefix: {
svg: "http://www.w3.org/2000/svg",
xhtml: "http://www.w3.org/1999/xhtml",
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
},
qualify: function(name) {
var i = name.indexOf(":");
return i < 0 ? name : {
space: d3.ns.prefix[name.substring(0, i)],
local: name.substring(i + 1)
};
}
};
/** @param {...string} types */
d3.dispatch = function(types) {
var dispatch = {},
type;
for (var i = 0, n = arguments.length; i < n; i++) {
type = arguments[i];
dispatch[type] = d3_dispatch(type);
}
return dispatch;
};
function d3_dispatch(type) {
var dispatch = {},
listeners = [];
dispatch.add = function(listener) {
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].listener == listener) return dispatch; // already registered
}
listeners.push({listener: listener, on: true});
return dispatch;
};
dispatch.remove = function(listener) {
for (var i = 0; i < listeners.length; i++) {
var l = listeners[i];
if (l.listener == listener) {
l.on = false;
listeners = listeners.slice(0, i).concat(listeners.slice(i + 1));
break;
}
}
return dispatch;
};
dispatch.dispatch = function() {
var ls = listeners; // defensive reference
for (var i = 0, n = ls.length; i < n; i++) {
var l = ls[i];
if (l.on) l.listener.apply(this, arguments);
}
};
return dispatch;
};
// TODO align
d3.format = function(specifier) {
var match = d3_format_re.exec(specifier),
fill = match[1] || " ",
sign = match[3] || "",
zfill = match[5],
width = +match[6],
comma = match[7],
precision = match[8],
type = match[9],
percentage = false,
integer = false;
if (precision) precision = precision.substring(1);
if (zfill) {
fill = "0"; // TODO align = "=";
if (comma) width -= Math.floor((width - 1) / 4);
}
switch (type) {
case "n": comma = true; type = "g"; break;
case "%": percentage = true; type = "f"; break;
case "p": percentage = true; type = "r"; break;
case "d": integer = true; precision = "0"; break;
}
type = d3_format_types[type] || d3_format_typeDefault;
return function(value) {
var number = percentage ? value * 100 : +value,
negative = (number < 0) && (number = -number) ? "\u2212" : sign;
// Return the empty string for floats formatted as ints.
if (integer && (number % 1)) return "";
// Convert the input value to the desired precision.
value = type(number, precision);
// If the fill character is 0, the sign and group is applied after the fill.
if (zfill) {
var length = value.length + negative.length;
if (length < width) value = new Array(width - length + 1).join(fill) + value;
if (comma) value = d3_format_group(value);
value = negative + value;
}
// Otherwise (e.g., space-filling), the sign and group is applied before.
else {
if (comma) value = d3_format_group(value);
value = negative + value;
var length = value.length;
if (length < width) value = new Array(width - length + 1).join(fill) + value;
}
if (percentage) value += "%";
return value;
};
};
// [[fill]align][sign][#][0][width][,][.precision][type]
var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/;
var d3_format_types = {
g: function(x, p) { return x.toPrecision(p); },
e: function(x, p) { return x.toExponential(p); },
f: function(x, p) { return x.toFixed(p); },
r: function(x, p) {
var n = x ? 1 + Math.floor(1e-15 + Math.log(x) / Math.LN10) : 1;
return d3.round(x, p - n).toFixed(Math.max(0, Math.min(20, p - n)));
}
};
function d3_format_typeDefault(x) {
return x + "";
}
// Apply comma grouping for thousands.
function d3_format_group(value) {
var i = value.lastIndexOf("."),
f = i >= 0 ? value.substring(i) : (i = value.length, ""),
t = [];
while (i > 0) t.push(value.substring(i -= 3, i + 3));
return t.reverse().join(",") + f;
}
/*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the author nor the names of contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
var d3_ease_quad = d3_ease_poly(2),
d3_ease_cubic = d3_ease_poly(3);
var d3_ease = {
linear: function() { return d3_ease_linear; },
poly: d3_ease_poly,
quad: function() { return d3_ease_quad; },
cubic: function() { return d3_ease_cubic; },
sin: function() { return d3_ease_sin; },
exp: function() { return d3_ease_exp; },
circle: function() { return d3_ease_circle; },
elastic: d3_ease_elastic,
back: d3_ease_back,
bounce: function() { return d3_ease_bounce; }
};
var d3_ease_mode = {
"in": function(f) { return f; },
"out": d3_ease_reverse,
"in-out": d3_ease_reflect,
"out-in": function(f) { return d3_ease_reflect(d3_ease_reverse(f)); }
};
d3.ease = function(name) {
var i = name.indexOf("-"),
t = i >= 0 ? name.substring(0, i) : name,
m = i >= 0 ? name.substring(i + 1) : "in";
return d3_ease_clamp(d3_ease_mode[m](d3_ease[t].apply(null, Array.prototype.slice.call(arguments, 1))));
};
function d3_ease_clamp(f) {
return function(t) {
return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
};
}
function d3_ease_reverse(f) {
return function(t) {
return 1 - f(1 - t);
};
}
function d3_ease_reflect(f) {
return function(t) {
return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t)));
};
}
function d3_ease_linear(t) {
return t;
}
function d3_ease_poly(e) {
return function(t) {
return Math.pow(t, e);
}
}
function d3_ease_sin(t) {
return 1 - Math.cos(t * Math.PI / 2);
}
function d3_ease_exp(t) {
return Math.pow(2, 10 * (t - 1));
}
function d3_ease_circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
function d3_ease_elastic(a, p) {
var s;
if (arguments.length < 2) p = 0.45;
if (arguments.length < 1) { a = 1; s = p / 4; }
else s = p / (2 * Math.PI) * Math.asin(1 / a);
return function(t) {
return 1 + a * Math.pow(2, 10 * -t) * Math.sin((t - s) * 2 * Math.PI / p);
};
}
function d3_ease_back(s) {
if (!s) s = 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
}
function d3_ease_bounce(t) {
return t < 1 / 2.75 ? 7.5625 * t * t
: t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75
: t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375
: 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
}
d3.event = null;
d3.interpolate = function(a, b) {
var i = d3.interpolators.length, f;
while (--i >= 0 && !(f = d3.interpolators[i](a, b)));
return f;
};
d3.interpolateNumber = function(a, b) {
b -= a;
return function(t) { return a + b * t; };
};
d3.interpolateRound = function(a, b) {
b -= a;
return function(t) { return Math.round(a + b * t); };
};
d3.interpolateString = function(a, b) {
var m, // current match
i, // current index
j, // current index (for coallescing)
s0 = 0, // start index of current string prefix
s1 = 0, // end index of current string prefix
s = [], // string constants and placeholders
q = [], // number interpolators
n, // q.length
o;
// Reset our regular expression!
d3_interpolate_number.lastIndex = 0;
// Find all numbers in b.
for (i = 0; m = d3_interpolate_number.exec(b); ++i) {
if (m.index) s.push(b.substring(s0, s1 = m.index));
q.push({i: s.length, x: m[0]});
s.push(null);
s0 = d3_interpolate_number.lastIndex;
}
if (s0 < b.length) s.push(b.substring(s0));
// Find all numbers in a.
for (i = 0, n = q.length; (m = d3_interpolate_number.exec(a)) && i < n; ++i) {
o = q[i];
if (o.x == m[0]) { // The numbers match, so coallesce.
if (o.i) {
if (s[o.i + 1] == null) { // This match is followed by another number.
s[o.i - 1] += o.x;
s.splice(o.i, 1);
for (j = i + 1; j < n; ++j) q[j].i--;
} else { // This match is followed by a string, so coallesce twice.
s[o.i - 1] += o.x + s[o.i + 1];
s.splice(o.i, 2);
for (j = i + 1; j < n; ++j) q[j].i -= 2;
}
} else {
if (s[o.i + 1] == null) { // This match is followed by another number.
s[o.i] = o.x;
} else { // This match is followed by a string, so coallesce twice.
s[o.i] = o.x + s[o.i + 1];
s.splice(o.i + 1, 1);
for (j = i + 1; j < n; ++j) q[j].i--;
}
}
q.splice(i, 1);
n--;
i--;
} else {
o.x = d3.interpolateNumber(parseFloat(m[0]), parseFloat(o.x));
}
}
// Remove any numbers in b not found in a.
while (i < n) {
o = q.pop();
if (s[o.i + 1] == null) { // This match is followed by another number.
s[o.i] = o.x;
} else { // This match is followed by a string, so coallesce twice.
s[o.i] = o.x + s[o.i + 1];
s.splice(o.i + 1, 1);
}
n--;
}
// Special optimization for only a single match.
if (s.length === 1) {
return s[0] == null ? q[0].x : function() { return b; };
}
// Otherwise, interpolate each of the numbers and rejoin the string.
return function(t) {
for (i = 0; i < n; ++i) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
};
d3.interpolateRgb = function(a, b) {
a = d3.rgb(a);
b = d3.rgb(b);
var ar = a.r,
ag = a.g,
ab = a.b,
br = b.r - ar,
bg = b.g - ag,
bb = b.b - ab;
return function(t) {
return "rgb(" + Math.round(ar + br * t)
+ "," + Math.round(ag + bg * t)
+ "," + Math.round(ab + bb * t)
+ ")";
};
};
// interpolates HSL space, but outputs RGB string (for compatibility)
d3.interpolateHsl = function(a, b) {
a = d3.hsl(a);
b = d3.hsl(b);
var h0 = a.h,
s0 = a.s,
l0 = a.l,
h1 = b.h - h0,
s1 = b.s - s0,
l1 = b.l - l0;
return function(t) {
return d3_hsl_rgb(h0 + h1 * t, s0 + s1 * t, l0 + l1 * t).toString();
};
};
d3.interpolateArray = function(a, b) {
var x = [],
c = [],
na = a.length,
nb = b.length,
n0 = Math.min(a.length, b.length),
i;
for (i = 0; i < n0; ++i) x.push(d3.interpolate(a[i], b[i]));
for (; i < na; ++i) c[i] = a[i];
for (; i < nb; ++i) c[i] = b[i];
return function(t) {
for (i = 0; i < n0; ++i) c[i] = x[i](t);
return c;
};
};
d3.interpolateObject = function(a, b) {
var i = {},
c = {},
k;
for (k in a) {
if (k in b) {
i[k] = d3_interpolateByName(k)(a[k], b[k]);
} else {
c[k] = a[k];
}
}
for (k in b) {
if (!(k in a)) {
c[k] = b[k];
}
}
return function(t) {
for (k in i) c[k] = i[k](t);
return c;
};
}
var d3_interpolate_number = /[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,
d3_interpolate_rgb = {background: 1, fill: 1, stroke: 1};
function d3_interpolateByName(n) {
return n in d3_interpolate_rgb || /\bcolor\b/.test(n)
? d3.interpolateRgb
: d3.interpolate;
}
d3.interpolators = [
d3.interpolateObject,
function(a, b) { return (b instanceof Array) && d3.interpolateArray(a, b); },
function(a, b) { return (typeof b === "string") && d3.interpolateString(String(a), b); },
function(a, b) { return (typeof b === "string" ? b in d3_rgb_names || /^(#|rgb\(|hsl\()/.test(b) : b instanceof d3_Rgb || b instanceof d3_Hsl) && d3.interpolateRgb(String(a), b); },
function(a, b) { return (typeof b === "number") && d3.interpolateNumber(+a, b); }
];
function d3_uninterpolateNumber(a, b) {
b = b - (a = +a) ? 1 / (b - a) : 0;
return function(x) { return (x - a) * b; };
}
function d3_uninterpolateClamp(a, b) {
b = b - (a = +a) ? 1 / (b - a) : 0;
return function(x) { return Math.max(0, Math.min(1, (x - a) * b)); };
}
d3.rgb = function(r, g, b) {
return arguments.length === 1
? d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb)
: d3_rgb(~~r, ~~g, ~~b);
};
function d3_rgb(r, g, b) {
return new d3_Rgb(r, g, b);
}
function d3_Rgb(r, g, b) {
this.r = r;
this.g = g;
this.b = b;
}
d3_Rgb.prototype.brighter = function(k) {
k = Math.pow(0.7, arguments.length ? k : 1);
var r = this.r,
g = this.g,
b = this.b,
i = 30;
if (!r && !g && !b) return d3_rgb(i, i, i);
if (r && r < i) r = i;
if (g && g < i) g = i;
if (b && b < i) b = i;
return d3_rgb(
Math.min(255, Math.floor(r / k)),
Math.min(255, Math.floor(g / k)),
Math.min(255, Math.floor(b / k)));
};
d3_Rgb.prototype.darker = function(k) {
k = Math.pow(0.7, arguments.length ? k : 1);
return d3_rgb(
Math.max(0, Math.floor(k * this.r)),
Math.max(0, Math.floor(k * this.g)),
Math.max(0, Math.floor(k * this.b)));
};
d3_Rgb.prototype.hsl = function() {
return d3_rgb_hsl(this.r, this.g, this.b);
};
d3_Rgb.prototype.toString = function() {
return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
};
function d3_rgb_hex(v) {
return v < 0x10 ? "0" + v.toString(16) : v.toString(16);
}
function d3_rgb_parse(format, rgb, hsl) {
var r = 0, // red channel; int in [0, 255]
g = 0, // green channel; int in [0, 255]
b = 0, // blue channel; int in [0, 255]
m1, // CSS color specification match
m2, // CSS color specification type (e.g., rgb)
name;
/* Handle hsl, rgb. */
m1 = /([a-z]+)\((.*)\)/i.exec(format);
if (m1) {
m2 = m1[2].split(",");
switch (m1[1]) {
case "hsl": {
return hsl(
parseFloat(m2[0]), // degrees
parseFloat(m2[1]) / 100, // percentage
parseFloat(m2[2]) / 100 // percentage
);
}
case "rgb": {
return rgb(
d3_rgb_parseNumber(m2[0]),
d3_rgb_parseNumber(m2[1]),
d3_rgb_parseNumber(m2[2])
);
}
}
}
/* Named colors. */
if (name = d3_rgb_names[format]) return rgb(name.r, name.g, name.b);
/* Hexadecimal colors: #rgb and #rrggbb. */
if (format != null && format.charAt(0) === "#") {
if (format.length === 4) {
r = format.charAt(1); r += r;
g = format.charAt(2); g += g;
b = format.charAt(3); b += b;
} else if (format.length === 7) {
r = format.substring(1, 3);
g = format.substring(3, 5);
b = format.substring(5, 7);
}
r = parseInt(r, 16);
g = parseInt(g, 16);
b = parseInt(b, 16);
}
return rgb(r, g, b);
}
function d3_rgb_hsl(r, g, b) {
var min = Math.min(r /= 255, g /= 255, b /= 255),
max = Math.max(r, g, b),
d = max - min,
h,
s,
l = (max + min) / 2;
if (d) {
s = l < .5 ? d / (max + min) : d / (2 - max - min);
if (r == max) h = (g - b) / d + (g < b ? 6 : 0);
else if (g == max) h = (b - r) / d + 2;
else h = (r - g) / d + 4;
h *= 60;
} else {
s = h = 0;
}
return d3_hsl(h, s, l);
}
function d3_rgb_parseNumber(c) { // either integer or percentage
var f = parseFloat(c);
return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
}
var d3_rgb_names = {
aliceblue: "#f0f8ff",
antiquewhite: "#faebd7",
aqua: "#00ffff",
aquamarine: "#7fffd4",
azure: "#f0ffff",
beige: "#f5f5dc",
bisque: "#ffe4c4",
black: "#000000",
blanchedalmond: "#ffebcd",
blue: "#0000ff",
blueviolet: "#8a2be2",
brown: "#a52a2a",
burlywood: "#deb887",
cadetblue: "#5f9ea0",
chartreuse: "#7fff00",
chocolate: "#d2691e",
coral: "#ff7f50",
cornflowerblue: "#6495ed",
cornsilk: "#fff8dc",
crimson: "#dc143c",
cyan: "#00ffff",
darkblue: "#00008b",
darkcyan: "#008b8b",
darkgoldenrod: "#b8860b",
darkgray: "#a9a9a9",
darkgreen: "#006400",
darkgrey: "#a9a9a9",
darkkhaki: "#bdb76b",
darkmagenta: "#8b008b",
darkolivegreen: "#556b2f",
darkorange: "#ff8c00",
darkorchid: "#9932cc",
darkred: "#8b0000",
darksalmon: "#e9967a",
darkseagreen: "#8fbc8f",
darkslateblue: "#483d8b",
darkslategray: "#2f4f4f",
darkslategrey: "#2f4f4f",
darkturquoise: "#00ced1",
darkviolet: "#9400d3",
deeppink: "#ff1493",
deepskyblue: "#00bfff",
dimgray: "#696969",
dimgrey: "#696969",
dodgerblue: "#1e90ff",
firebrick: "#b22222",
floralwhite: "#fffaf0",
forestgreen: "#228b22",
fuchsia: "#ff00ff",
gainsboro: "#dcdcdc",
ghostwhite: "#f8f8ff",
gold: "#ffd700",
goldenrod: "#daa520",
gray: "#808080",
green: "#008000",
greenyellow: "#adff2f",
grey: "#808080",
honeydew: "#f0fff0",
hotpink: "#ff69b4",
indianred: "#cd5c5c",
indigo: "#4b0082",
ivory: "#fffff0",
khaki: "#f0e68c",
lavender: "#e6e6fa",
lavenderblush: "#fff0f5",
lawngreen: "#7cfc00",
lemonchiffon: "#fffacd",
lightblue: "#add8e6",
lightcoral: "#f08080",
lightcyan: "#e0ffff",
lightgoldenrodyellow: "#fafad2",
lightgray: "#d3d3d3",
lightgreen: "#90ee90",
lightgrey: "#d3d3d3",
lightpink: "#ffb6c1",
lightsalmon: "#ffa07a",
lightseagreen: "#20b2aa",
lightskyblue: "#87cefa",
lightslategray: "#778899",
lightslategrey: "#778899",
lightsteelblue: "#b0c4de",
lightyellow: "#ffffe0",
lime: "#00ff00",
limegreen: "#32cd32",
linen: "#faf0e6",
magenta: "#ff00ff",
maroon: "#800000",
mediumaquamarine: "#66cdaa",
mediumblue: "#0000cd",
mediumorchid: "#ba55d3",
mediumpurple: "#9370db",
mediumseagreen: "#3cb371",
mediumslateblue: "#7b68ee",
mediumspringgreen: "#00fa9a",
mediumturquoise: "#48d1cc",
mediumvioletred: "#c71585",
midnightblue: "#191970",
mintcream: "#f5fffa",
mistyrose: "#ffe4e1",
moccasin: "#ffe4b5",
navajowhite: "#ffdead",
navy: "#000080",
oldlace: "#fdf5e6",
olive: "#808000",
olivedrab: "#6b8e23",
orange: "#ffa500",
orangered: "#ff4500",
orchid: "#da70d6",
palegoldenrod: "#eee8aa",
palegreen: "#98fb98",
paleturquoise: "#afeeee",
palevioletred: "#db7093",
papayawhip: "#ffefd5",
peachpuff: "#ffdab9",
peru: "#cd853f",
pink: "#ffc0cb",
plum: "#dda0dd",
powderblue: "#b0e0e6",
purple: "#800080",
red: "#ff0000",
rosybrown: "#bc8f8f",
royalblue: "#4169e1",
saddlebrown: "#8b4513",
salmon: "#fa8072",
sandybrown: "#f4a460",
seagreen: "#2e8b57",
seashell: "#fff5ee",
sienna: "#a0522d",
silver: "#c0c0c0",
skyblue: "#87ceeb",
slateblue: "#6a5acd",
slategray: "#708090",
slategrey: "#708090",
snow: "#fffafa",
springgreen: "#00ff7f",
steelblue: "#4682b4",
tan: "#d2b48c",
teal: "#008080",
thistle: "#d8bfd8",
tomato: "#ff6347",
turquoise: "#40e0d0",
violet: "#ee82ee",
wheat: "#f5deb3",
white: "#ffffff",
whitesmoke: "#f5f5f5",
yellow: "#ffff00",
yellowgreen: "#9acd32"
};
for (var d3_rgb_name in d3_rgb_names) {
d3_rgb_names[d3_rgb_name] = d3_rgb_parse(
d3_rgb_names[d3_rgb_name],
d3_rgb,
d3_hsl_rgb);
}
d3.hsl = function(h, s, l) {
return arguments.length === 1
? d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl)
: d3_hsl(+h, +s, +l);
};
function d3_hsl(h, s, l) {
return new d3_Hsl(h, s, l);
}
function d3_Hsl(h, s, l) {
this.h = h;
this.s = s;
this.l = l;
}
d3_Hsl.prototype.brighter = function(k) {
k = Math.pow(0.7, arguments.length ? k : 1);
return d3_hsl(this.h, this.s, this.l / k);
};
d3_Hsl.prototype.darker = function(k) {
k = Math.pow(0.7, arguments.length ? k : 1);
return d3_hsl(this.h, this.s, k * this.l);
};
d3_Hsl.prototype.rgb = function() {
return d3_hsl_rgb(this.h, this.s, this.l);
};
d3_Hsl.prototype.toString = function() {
return "hsl(" + this.h + "," + this.s * 100 + "%," + this.l * 100 + "%)";
};
function d3_hsl_rgb(h, s, l) {
var m1,
m2;
/* Some simple corrections for h, s and l. */
h = h % 360; if (h < 0) h += 360;
s = s < 0 ? 0 : s > 1 ? 1 : s;
l = l < 0 ? 0 : l > 1 ? 1 : l;
/* From FvD 13.37, CSS Color Module Level 3 */
m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
m1 = 2 * l - m2;
function v(h) {
if (h > 360) h -= 360;
else if (h < 0) h += 360;
if (h < 60) return m1 + (m2 - m1) * h / 60;
if (h < 180) return m2;
if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
return m1;
}
function vv(h) {
return Math.round(v(h) * 255);
}
return d3_rgb(vv(h + 120), vv(h), vv(h - 120));
}
function d3_selection(groups) {
d3_arraySubclass(groups, d3_selectionPrototype);
return groups;
}
var d3_select = function(s, n) { return n.querySelector(s); },
d3_selectAll = function(s, n) { return n.querySelectorAll(s); };
// Prefer Sizzle, if available.
if (typeof Sizzle === "function") {
d3_select = function(s, n) { return Sizzle(s, n)[0]; };
d3_selectAll = function(s, n) { return Sizzle.uniqueSort(Sizzle(s, n)); };
}
var d3_selectionPrototype = [];
d3.selection = function() {
return d3_selectionRoot;
};
d3.selection.prototype = d3_selectionPrototype;
d3_selectionPrototype.select = function(selector) {
var subgroups = [],
subgroup,
subnode,
group,
node;
if (typeof selector !== "function") selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m;) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = -1, n = group.length; ++i < n;) {
if (node = group[i]) {
subgroup.push(subnode = selector.call(node, node.__data__, i));
if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selector(selector) {
return function() {
return d3_select(selector, this);
};
}
d3_selectionPrototype.selectAll = function(selector) {
var subgroups = [],
subgroup,
node;
if (typeof selector !== "function") selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m;) {
for (var group = this[j], i = -1, n = group.length; ++i < n;) {
if (node = group[i]) {
subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i)));
subgroup.parentNode = node;
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selectorAll(selector) {
return function() {
return d3_selectAll(selector, this);
};
}
d3_selectionPrototype.attr = function(name, value) {
name = d3.ns.qualify(name);
// If no value is specified, return the first value.
if (arguments.length < 2) {
var node = this.node();
return name.local
? node.getAttributeNS(name.space, name.local)
: node.getAttribute(name);
}
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrConstant() {
this.setAttribute(name, value);
}
function attrConstantNS() {
this.setAttributeNS(name.space, name.local, value);
}
function attrFunction() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttribute(name);
else this.setAttribute(name, x);
}
function attrFunctionNS() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttributeNS(name.space, name.local);
else this.setAttributeNS(name.space, name.local, x);
}
return this.each(value == null
? (name.local ? attrNullNS : attrNull) : (typeof value === "function"
? (name.local ? attrFunctionNS : attrFunction)
: (name.local ? attrConstantNS : attrConstant)));
};
d3_selectionPrototype.classed = function(name, value) {
var re = new RegExp("(^|\\s+)" + d3.requote(name) + "(\\s+|$)", "g");
// If no value is specified, return the first value.
if (arguments.length < 2) {
var node = this.node();
if (c = node.classList) return c.contains(name);
var c = node.className;
re.lastIndex = 0;
return re.test(c.baseVal != null ? c.baseVal : c);
}
function classedAdd() {
if (c = this.classList) return c.add(name);
var c = this.className,
cb = c.baseVal != null,
cv = cb ? c.baseVal : c;
re.lastIndex = 0;
if (!re.test(cv)) {
cv = d3_collapse(cv + " " + name);
if (cb) c.baseVal = cv;
else this.className = cv;
}
}
function classedRemove() {
if (c = this.classList) return c.remove(name);
var c = this.className,
cb = c.baseVal != null,
cv = cb ? c.baseVal : c;
cv = d3_collapse(cv.replace(re, " "));
if (cb) c.baseVal = cv;
else this.className = cv;
}
function classedFunction() {
(value.apply(this, arguments)
? classedAdd
: classedRemove).call(this);
}
return this.each(typeof value === "function"
? classedFunction : value
? classedAdd
: classedRemove);
};
d3_selectionPrototype.style = function(name, value, priority) {
if (arguments.length < 3) priority = "";
// If no value is specified, return the first value.
if (arguments.length < 2) return window
.getComputedStyle(this.node(), null)
.getPropertyValue(name);
function styleNull() {
this.style.removeProperty(name);
}
function styleConstant() {
this.style.setProperty(name, value, priority);
}
function styleFunction() {
var x = value.apply(this, arguments);
if (x == null) this.style.removeProperty(name);
else this.style.setProperty(name, x, priority);
}
return this.each(value == null
? styleNull : (typeof value === "function"
? styleFunction : styleConstant));
};
d3_selectionPrototype.property = function(name, value) {
// If no value is specified, return the first value.
if (arguments.length < 2) return this.node()[name];
function propertyNull() {
delete this[name];
}
function propertyConstant() {
this[name] = value;
}
function propertyFunction() {
var x = value.apply(this, arguments);
if (x == null) delete this[name];
else this[name] = x;
}
return this.each(value == null
? propertyNull : (typeof value === "function"
? propertyFunction : propertyConstant));
};
d3_selectionPrototype.text = function(value) {
return arguments.length < 1 ? this.node().textContent
: (this.each(typeof value === "function"
? function() { this.textContent = value.apply(this, arguments); }
: function() { this.textContent = value; }));
};
d3_selectionPrototype.html = function(value) {
return arguments.length < 1 ? this.node().innerHTML
: (this.each(typeof value === "function"
? function() { this.innerHTML = value.apply(this, arguments); }
: function() { this.innerHTML = value; }));
};
// TODO append(node)?
// TODO append(function)?
d3_selectionPrototype.append = function(name) {
name = d3.ns.qualify(name);
function append() {
return this.appendChild(document.createElement(name));
}
function appendNS() {
return this.appendChild(document.createElementNS(name.space, name.local));
}
return this.select(name.local ? appendNS : append);
};
// TODO insert(node, function)?
// TODO insert(function, string)?
// TODO insert(function, function)?
d3_selectionPrototype.insert = function(name, before) {
name = d3.ns.qualify(name);
function insert() {
return this.insertBefore(
document.createElement(name),
d3_select(before, this));
}
function insertNS() {
return this.insertBefore(
document.createElementNS(name.space, name.local),
d3_select(before, this));
}
return this.select(name.local ? insertNS : insert);
};
// TODO remove(selector)?
// TODO remove(node)?
// TODO remove(function)?
d3_selectionPrototype.remove = function() {
return this.each(function() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
});
};
// TODO data(null) for clearing data?
d3_selectionPrototype.data = function(data, join) {
var enter = [],
update = [],
exit = [];
function bind(group, groupData) {
var i,
n = group.length,
m = groupData.length,
n0 = Math.min(n, m),
n1 = Math.max(n, m),
updateNodes = [],
enterNodes = [],
exitNodes = [],
node,
nodeData;
if (join) {
var nodeByKey = {},
keys = [],
key,
j = groupData.length;
for (i = -1; ++i < n;) {
key = join.call(node = group[i], node.__data__, i);
if (key in nodeByKey) {
exitNodes[j++] = node; // duplicate key
} else {
nodeByKey[key] = node;
}
keys.push(key);
}
for (i = -1; ++i < m;) {
node = nodeByKey[key = join.call(groupData, nodeData = groupData[i], i)];
if (node) {
node.__data__ = nodeData;
updateNodes[i] = node;
enterNodes[i] = exitNodes[i] = null;
} else {
enterNodes[i] = d3_selection_dataNode(nodeData);
updateNodes[i] = exitNodes[i] = null;
}
delete nodeByKey[key];
}
for (i = -1; ++i < n;) {
if (keys[i] in nodeByKey) {
exitNodes[i] = group[i];
}
}
} else {
for (i = -1; ++i < n0;) {
node = group[i];
nodeData = groupData[i];
if (node) {
node.__data__ = nodeData;
updateNodes[i] = node;
enterNodes[i] = exitNodes[i] = null;
} else {
enterNodes[i] = d3_selection_dataNode(nodeData);
updateNodes[i] = exitNodes[i] = null;
}
}
for (; i < m; ++i) {
enterNodes[i] = d3_selection_dataNode(groupData[i]);
updateNodes[i] = exitNodes[i] = null;
}
for (; i < n1; ++i) {
exitNodes[i] = group[i];
enterNodes[i] = updateNodes[i] = null;
}
}
enterNodes.update
= updateNodes;
enterNodes.parentNode
= updateNodes.parentNode
= exitNodes.parentNode
= group.parentNode;
enter.push(enterNodes);
update.push(updateNodes);
exit.push(exitNodes);
}
var i = -1,
n = this.length,
group;
if (typeof data === "function") {
while (++i < n) {
bind(group = this[i], data.call(group, group.parentNode.__data__, i));
}
} else {
while (++i < n) {
bind(group = this[i], data);
}
}
var selection = d3_selection(update);
selection.enter = function() { return d3_selection_enter(enter); };
selection.exit = function() { return d3_selection(exit); };
return selection;
};
function d3_selection_dataNode(data) {
return {__data__: data};
}
function d3_selection_enter(selection) {
d3_arraySubclass(selection, d3_selection_enterPrototype);
return selection;
}
var d3_selection_enterPrototype = [];
d3_selection_enterPrototype.append = d3_selectionPrototype.append;
d3_selection_enterPrototype.insert = d3_selectionPrototype.insert;
d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
d3_selection_enterPrototype.select = function(selector) {
var subgroups = [],
subgroup,
subnode,
upgroup,
group,
node;
for (var j = -1, m = this.length; ++j < m;) {
upgroup = (group = this[j]).update;
subgroups.push(subgroup = []);
subgroup.parentNode = group.parentNode;
for (var i = -1, n = group.length; ++i < n;) {
if (node = group[i]) {
subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i));
subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
// TODO preserve null elements to maintain index?
d3_selectionPrototype.filter = function(filter) {
var subgroups = [],
subgroup,
group,
node;
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i)) {
subgroup.push(node);
}
}
}
return d3_selection(subgroups);
};
d3_selectionPrototype.map = function(map) {
return this.each(function() {
this.__data__ = map.apply(this, arguments);
});
};
d3_selectionPrototype.sort = function(comparator) {
comparator = d3_selection_sortComparator.apply(this, arguments);
for (var j = 0, m = this.length; j < m; j++) {
for (var group = this[j].sort(comparator), i = 1, n = group.length, prev = group[0]; i < n; i++) {
var node = group[i];
if (node) {
if (prev) prev.parentNode.insertBefore(node, prev.nextSibling);
prev = node;
}
}
}
return this;
};
function d3_selection_sortComparator(comparator) {
if (!arguments.length) comparator = d3.ascending;
return function(a, b) {
return comparator(a && a.__data__, b && b.__data__);
};
}
// type can be namespaced, e.g., "click.foo"
// listener can be null for removal
d3_selectionPrototype.on = function(type, listener, capture) {
if (arguments.length < 3) capture = false;
// parse the type specifier
var name = "__on" + type, i = type.indexOf(".");
if (i > 0) type = type.substring(0, i);
// if called with only one argument, return the current listener
if (arguments.length < 2) return (i = this.node()[name]) && i._;
// remove the old event listener, and add the new event listener
return this.each(function(d, i) {
var node = this;
if (node[name]) node.removeEventListener(type, node[name], capture);
if (listener) node.addEventListener(type, node[name] = l, capture);
// wrapped event listener that preserves i
function l(e) {
var o = d3.event; // Events can be reentrant (e.g., focus).
d3.event = e;
try {
listener.call(node, node.__data__, i);
} finally {
d3.event = o;
}
}
// stash the unwrapped listener for retrieval
l._ = listener;
});
};
d3_selectionPrototype.each = function(callback) {
for (var j = -1, m = this.length; ++j < m;) {
for (var group = this[j], i = -1, n = group.length; ++i < n;) {
var node = group[i];
if (node) callback.call(node, node.__data__, i, j);
}
}
return this;
};
//
// Note: assigning to the arguments array simultaneously changes the value of
// the corresponding argument!
//
// TODO The `this` argument probably shouldn't be the first argument to the
// callback, anyway, since it's redundant. However, that will require a major
// version bump due to backwards compatibility, so I'm not changing it right
// away.
//
d3_selectionPrototype.call = function(callback) {
callback.apply(this, (arguments[0] = this, arguments));
return this;
};
d3_selectionPrototype.empty = function() {
return !this.node();
};
d3_selectionPrototype.node = function(callback) {
for (var j = 0, m = this.length; j < m; j++) {
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
var node = group[i];
if (node) return node;
}
}
return null;
};
d3_selectionPrototype.transition = function() {
var subgroups = [],
subgroup,
node;
for (var j = -1, m = this.length; ++j < m;) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n;) {
subgroup.push((node = group[i]) ? {node: node, delay: 0, duration: 250} : null);
}
}
return d3_transition(subgroups, d3_transitionInheritId || ++d3_transitionId);
};
var d3_selectionRoot = d3_selection([[document]]);
d3_selectionRoot[0].parentNode = document.documentElement;
// TODO fast singleton implementation!
// TODO select(function)
d3.select = function(selector) {
return typeof selector === "string"
? d3_selectionRoot.select(selector)
: d3_selection([[selector]]); // assume node
};
// TODO selectAll(function)
d3.selectAll = function(selector) {
return typeof selector === "string"
? d3_selectionRoot.selectAll(selector)
: d3_selection([d3_array(selector)]); // assume node[]
};
function d3_transition(groups, id) {
d3_arraySubclass(groups, d3_transitionPrototype);
var tweens = {},
event = d3.dispatch("start", "end"),
ease = d3_transitionEase,
then = Date.now();
groups.id = id;
groups.tween = function(name, tween) {
if (arguments.length < 2) return tweens[name];
if (tween == null) delete tweens[name];
else tweens[name] = tween;
return groups;
};
groups.ease = function(value) {
if (!arguments.length) return ease;
ease = typeof value === "function" ? value : d3.ease.apply(d3, arguments);
return groups;
};
groups.each = function(type, listener) {
if (arguments.length < 2) return d3_transition_each.call(groups, type);
event[type].add(listener);
return groups;
};
d3.timer(function(elapsed) {
groups.each(function(d, i, j) {
var tweened = [],
node = this,
delay = groups[j][i].delay,
duration = groups[j][i].duration,
lock = node.__transition__ || (node.__transition__ = {active: 0, count: 0});
++lock.count;
delay <= elapsed ? start(elapsed) : d3.timer(start, delay, then);
function start(elapsed) {
if (lock.active > id) return stop();
lock.active = id;
for (var tween in tweens) {
if (tween = tweens[tween].call(node, d, i)) {
tweened.push(tween);
}
}
event.start.dispatch.call(node, d, i);
if (!tick(elapsed)) d3.timer(tick, 0, then);
return 1;
}
function tick(elapsed) {
if (lock.active !== id) return stop();
var t = (elapsed - delay) / duration,
e = ease(t),
n = tweened.length;
while (n > 0) {
tweened[--n].call(node, e);
}
if (t >= 1) {
stop();
d3_transitionInheritId = id;
event.end.dispatch.call(node, d, i);
d3_transitionInheritId = 0;
return 1;
}
}
function stop() {
if (!--lock.count) delete node.__transition__;
return 1;
}
});
return 1;
}, 0, then);
return groups;
}
function d3_transitionTween(b) {
return typeof b === "function"
? function(d, i, a) { var v = b.call(this, d, i) + ""; return a != v && d3.interpolate(a, v); }
: (b = b + "", function(d, i, a) { return a != b && d3.interpolate(a, b); });
}
var d3_transitionPrototype = [],
d3_transitionId = 0,
d3_transitionInheritId = 0,
d3_transitionEase = d3.ease("cubic-in-out");
d3_transitionPrototype.call = d3_selectionPrototype.call;
d3.transition = function() {
return d3_selectionRoot.transition();
};
d3.transition.prototype = d3_transitionPrototype;
d3_transitionPrototype.select = function(selector) {
var subgroups = [],
subgroup,
subnode,
node;
if (typeof selector !== "function") selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m;) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n;) {
if ((node = group[i]) && (subnode = selector.call(node.node, node.node.__data__, i))) {
if ("__data__" in node.node) subnode.__data__ = node.node.__data__;
subgroup.push({node: subnode, delay: node.delay, duration: node.duration});
} else {
subgroup.push(null);
}
}
}
return d3_transition(subgroups, this.id).ease(this.ease());
};
d3_transitionPrototype.selectAll = function(selector) {
var subgroups = [],
subgroup,
subnodes,
node;
if (typeof selector !== "function") selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m;) {
for (var group = this[j], i = -1, n = group.length; ++i < n;) {
if (node = group[i]) {
subnodes = selector.call(node.node, node.node.__data__, i);
subgroups.push(subgroup = []);
for (var k = -1, o = subnodes.length; ++k < o;) {
subgroup.push({node: subnodes[k], delay: node.delay, duration: node.duration});
}
}
}
}
return d3_transition(subgroups, this.id).ease(this.ease());
};
d3_transitionPrototype.attr = function(name, value) {
return this.attrTween(name, d3_transitionTween(value));
};
d3_transitionPrototype.attrTween = function(name, tween) {
name = d3.ns.qualify(name);
function attrTween(d, i) {
var f = tween.call(this, d, i, this.getAttribute(name));
return f && function(t) {
this.setAttribute(name, f(t));
};
}
function attrTweenNS(d, i) {
var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
return f && function(t) {
this.setAttributeNS(name.space, name.local, f(t));
};
}
return this.tween("attr." + name, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.style = function(name, value, priority) {
if (arguments.length < 3) priority = "";
return this.styleTween(name, d3_transitionTween(value), priority);
};
d3_transitionPrototype.styleTween = function(name, tween, priority) {
if (arguments.length < 3) priority = "";
return this.tween("style." + name, function(d, i) {
var f = tween.call(this, d, i, window.getComputedStyle(this, null).getPropertyValue(name));
return f && function(t) {
this.style.setProperty(name, f(t), priority);
};
});
};
d3_transitionPrototype.text = function(value) {
return this.tween("text", function(d, i) {
this.textContent = typeof value === "function"
? value.call(this, d, i)
: value;
});
};
d3_transitionPrototype.remove = function() {
return this.each("end", function() {
var p;
if (!this.__transition__ && (p = this.parentNode)) p.removeChild(this);
});
};
d3_transitionPrototype.delay = function(value) {
var groups = this;
return groups.each(typeof value === "function"
? function(d, i, j) { groups[j][i].delay = +value.apply(this, arguments); }
: (value = +value, function(d, i, j) { groups[j][i].delay = value; }));
};
d3_transitionPrototype.duration = function(value) {
var groups = this;
return groups.each(typeof value === "function"
? function(d, i, j) { groups[j][i].duration = +value.apply(this, arguments); }
: (value = +value, function(d, i, j) { groups[j][i].duration = value; }));
};
function d3_transition_each(callback) {
for (var j = 0, m = this.length; j < m; j++) {
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
var node = group[i];
if (node) callback.call(node = node.node, node.__data__, i, j);
}
}
return this;
}
d3_transitionPrototype.transition = function() {
return this.select(d3_this);
};
var d3_timer_queue = null,
d3_timer_interval, // is an interval (or frame) active?
d3_timer_timeout; // is a timeout active?
// The timer will continue to fire until callback returns true.
d3.timer = function(callback, delay, then) {
var found = false,
t0,
t1 = d3_timer_queue;
if (arguments.length < 3) {
if (arguments.length < 2) delay = 0;
else if (!isFinite(delay)) return;
then = Date.now();
}
// See if the callback's already in the queue.
while (t1) {
if (t1.callback === callback) {
t1.then = then;
t1.delay = delay;
found = true;
break;
}
t0 = t1;
t1 = t1.next;
}
// Otherwise, add the callback to the queue.
if (!found) d3_timer_queue = {
callback: callback,
then: then,
delay: delay,
next: d3_timer_queue
};
// Start animatin'!
if (!d3_timer_interval) {
d3_timer_timeout = clearTimeout(d3_timer_timeout);
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
}
function d3_timer_step() {
var elapsed,
now = Date.now(),
t1 = d3_timer_queue;
while (t1) {
elapsed = now - t1.then;
if (elapsed >= t1.delay) t1.flush = t1.callback(elapsed);
t1 = t1.next;
}
var delay = d3_timer_flush() - now;
if (delay > 24) {
if (isFinite(delay)) {
clearTimeout(d3_timer_timeout);
d3_timer_timeout = setTimeout(d3_timer_step, delay);
}
d3_timer_interval = 0;
} else {
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
}
d3.timer.flush = function() {
var elapsed,
now = Date.now(),
t1 = d3_timer_queue;
while (t1) {
elapsed = now - t1.then;
if (!t1.delay) t1.flush = t1.callback(elapsed);
t1 = t1.next;
}
d3_timer_flush();
};
// Flush after callbacks, to avoid concurrent queue modification.
function d3_timer_flush() {
var t0 = null,
t1 = d3_timer_queue,
then = Infinity;
while (t1) {
if (t1.flush) {
t1 = t0 ? t0.next = t1.next : d3_timer_queue = t1.next;
} else {
then = Math.min(then, t1.then + t1.delay);
t1 = (t0 = t1).next;
}
}
return then;
}
var d3_timer_frame = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 17); };
function d3_noop() {}
d3.scale = {};
function d3_scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [start, stop] : [stop, start];
}
function d3_scale_nice(domain, nice) {
var i0 = 0,
i1 = domain.length - 1,
x0 = domain[i0],
x1 = domain[i1],
dx;
if (x1 < x0) {
dx = i0; i0 = i1; i1 = dx;
dx = x0; x0 = x1; x1 = dx;
}
nice = nice(x1 - x0);
domain[i0] = nice.floor(x0);
domain[i1] = nice.ceil(x1);
return domain;
}
function d3_scale_niceDefault() {
return Math;
}
d3.scale.linear = function() {
return d3_scale_linear([0, 1], [0, 1], d3.interpolate, false);
};
function d3_scale_linear(domain, range, interpolate, clamp) {
var output,
input;
function rescale() {
var linear = domain.length == 2 ? d3_scale_bilinear : d3_scale_polylinear,
uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
output = linear(domain, range, uninterpolate, interpolate);
input = linear(range, domain, uninterpolate, d3.interpolate);
return scale;
}
function scale(x) {
return output(x);
}
// Note: requires range is coercible to number!
scale.invert = function(y) {
return input(y);
};
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.map(Number);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.rangeRound = function(x) {
return scale.range(x).interpolate(d3.interpolateRound);
};
scale.clamp = function(x) {
if (!arguments.length) return clamp;
clamp = x;
return rescale();
};
scale.interpolate = function(x) {
if (!arguments.length) return interpolate;
interpolate = x;
return rescale();
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m) {
return d3_scale_linearTickFormat(domain, m);
};
scale.nice = function() {
d3_scale_nice(domain, d3_scale_linearNice);
return rescale();
};
scale.copy = function() {
return d3_scale_linear(domain, range, interpolate, clamp);
};
return rescale();
};
function d3_scale_linearRebind(scale, linear) {
scale.range = d3.rebind(scale, linear.range);
scale.rangeRound = d3.rebind(scale, linear.rangeRound);
scale.interpolate = d3.rebind(scale, linear.interpolate);
scale.clamp = d3.rebind(scale, linear.clamp);
return scale;
}
function d3_scale_linearNice(dx) {
dx = Math.pow(10, Math.round(Math.log(dx) / Math.LN10) - 1);
return {
floor: function(x) { return Math.floor(x / dx) * dx; },
ceil: function(x) { return Math.ceil(x / dx) * dx; }
};
}
// TODO Dates? Ugh.
function d3_scale_linearTickRange(domain, m) {
var extent = d3_scaleExtent(domain),
span = extent[1] - extent[0],
step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)),
err = m / span * step;
// Filter ticks to get closer to the desired count.
if (err <= .15) step *= 10;
else if (err <= .35) step *= 5;
else if (err <= .75) step *= 2;
// Round start and stop values to step interval.
extent[0] = Math.ceil(extent[0] / step) * step;
extent[1] = Math.floor(extent[1] / step) * step + step * .5; // inclusive
extent[2] = step;
return extent;
}
function d3_scale_linearTicks(domain, m) {
return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
}
function d3_scale_linearTickFormat(domain, m) {
return d3.format(",." + Math.max(0, -Math.floor(Math.log(d3_scale_linearTickRange(domain, m)[2]) / Math.LN10 + .01)) + "f");
}
function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
var u = uninterpolate(domain[0], domain[1]),
i = interpolate(range[0], range[1]);
return function(x) {
return i(u(x));
};
}
function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
var u = [],
i = [],
j = 0,
n = domain.length;
while (++j < n) {
u.push(uninterpolate(domain[j - 1], domain[j]));
i.push(interpolate(range[j - 1], range[j]));
}
return function(x) {
var j = d3.bisect(domain, x, 1, domain.length - 1) - 1;
return i[j](u[j](x));
};
}
d3.scale.log = function() {
return d3_scale_log(d3.scale.linear(), d3_scale_logp);
};
function d3_scale_log(linear, log) {
var pow = log.pow;
function scale(x) {
return linear(log(x));
}
scale.invert = function(x) {
return pow(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return linear.domain().map(pow);
log = x[0] < 0 ? d3_scale_logn : d3_scale_logp;
pow = log.pow;
linear.domain(x.map(log));
return scale;
};
scale.nice = function() {
linear.domain(d3_scale_nice(linear.domain(), d3_scale_niceDefault));
return scale;
};
scale.ticks = function() {
var extent = d3_scaleExtent(linear.domain()),
ticks = [];
if (extent.every(isFinite)) {
var i = Math.floor(extent[0]),
j = Math.ceil(extent[1]),
u = Math.round(pow(extent[0])),
v = Math.round(pow(extent[1]));
if (log === d3_scale_logn) {
ticks.push(pow(i));
for (; i++ < j;) for (var k = 9; k > 0; k--) ticks.push(pow(i) * k);
} else {
for (; i < j; i++) for (var k = 1; k < 10; k++) ticks.push(pow(i) * k);
ticks.push(pow(i));
}
for (i = 0; ticks[i] < u; i++) {} // strip small values
for (j = ticks.length; ticks[j - 1] > v; j--) {} // strip big values
ticks = ticks.slice(i, j);
}
return ticks;
};
scale.tickFormat = function(n, format) {
if (arguments.length < 2) format = d3_scale_logFormat;
if (arguments.length < 1) return format;
var k = n / scale.ticks().length,
f = log === d3_scale_logn ? (e = -1e-15, Math.floor) : (e = 1e-15, Math.ceil),
e;
return function(d) {
return d / pow(f(log(d) + e)) < k ? format(d) : "";
};
};
scale.copy = function() {
return d3_scale_log(linear.copy(), log);
};
return d3_scale_linearRebind(scale, linear);
};
var d3_scale_logFormat = d3.format("e");
function d3_scale_logp(x) {
return Math.log(x) / Math.LN10;
}
function d3_scale_logn(x) {
return -Math.log(-x) / Math.LN10;
}
d3_scale_logp.pow = function(x) {
return Math.pow(10, x);
};
d3_scale_logn.pow = function(x) {
return -Math.pow(10, -x);
};
d3.scale.pow = function() {
return d3_scale_pow(d3.scale.linear(), 1);
};
function d3_scale_pow(linear, exponent) {
var powp = d3_scale_powPow(exponent),
powb = d3_scale_powPow(1 / exponent);
function scale(x) {
return linear(powp(x));
}
scale.invert = function(x) {
return powb(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return linear.domain().map(powb);
linear.domain(x.map(powp));
return scale;
};
scale.ticks = function(m) {
return d3_scale_linearTicks(scale.domain(), m);
};
scale.tickFormat = function(m) {
return d3_scale_linearTickFormat(scale.domain(), m);
};
scale.nice = function() {
return scale.domain(d3_scale_nice(scale.domain(), d3_scale_linearNice));
};
scale.exponent = function(x) {
if (!arguments.length) return exponent;
var domain = scale.domain();
powp = d3_scale_powPow(exponent = x);
powb = d3_scale_powPow(1 / exponent);
return scale.domain(domain);
};
scale.copy = function() {
return d3_scale_pow(linear.copy(), exponent);
};
return d3_scale_linearRebind(scale, linear);
};
function d3_scale_powPow(e) {
return function(x) {
return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
};
}
d3.scale.sqrt = function() {
return d3.scale.pow().exponent(.5);
};
d3.scale.ordinal = function() {
return d3_scale_ordinal([], {t: "range", x: []});
};
function d3_scale_ordinal(domain, ranger) {
var index,
range,
rangeBand;
function scale(x) {
return range[((index[x] || (index[x] = domain.push(x))) - 1) % range.length];
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = [];
index = {};
var i = -1, n = x.length, xi;
while (++i < n) if (!index[xi = x[i]]) index[xi] = domain.push(xi);
return scale[ranger.t](ranger.x, ranger.p);
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
rangeBand = 0;
ranger = {t: "range", x: x};
return scale;
};
scale.rangePoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0],
stop = x[1],
step = (stop - start) / (domain.length - 1 + padding);
range = domain.length < 2 ? [(start + stop) / 2] : d3.range(start + step * padding / 2, stop + step / 2, step);
rangeBand = 0;
ranger = {t: "rangePoints", x: x, p: padding};
return scale;
};
scale.rangeBands = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0],
stop = x[1],
step = (stop - start) / (domain.length + padding);
range = d3.range(start + step * padding, stop, step);
rangeBand = step * (1 - padding);
ranger = {t: "rangeBands", x: x, p: padding};
return scale;
};
scale.rangeRoundBands = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0],
stop = x[1],
step = Math.floor((stop - start) / (domain.length + padding)),
err = stop - start - (domain.length - padding) * step;
range = d3.range(start + Math.round(err / 2), stop, step);
rangeBand = Math.round(step * (1 - padding));
ranger = {t: "rangeRoundBands", x: x, p: padding};
return scale;
};
scale.rangeBand = function() {
return rangeBand;
};
scale.copy = function() {
return d3_scale_ordinal(domain, ranger);
};
return scale.domain(domain);
};
/*
* This product includes color specifications and designs developed by Cynthia
* Brewer (http://colorbrewer.org/). See lib/colorbrewer for more information.
*/
d3.scale.category10 = function() {
return d3.scale.ordinal().range(d3_category10);
};
d3.scale.category20 = function() {
return d3.scale.ordinal().range(d3_category20);
};
d3.scale.category20b = function() {
return d3.scale.ordinal().range(d3_category20b);
};
d3.scale.category20c = function() {
return d3.scale.ordinal().range(d3_category20c);
};
var d3_category10 = [
"#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"
];
var d3_category20 = [
"#1f77b4", "#aec7e8",
"#ff7f0e", "#ffbb78",
"#2ca02c", "#98df8a",
"#d62728", "#ff9896",
"#9467bd", "#c5b0d5",
"#8c564b", "#c49c94",
"#e377c2", "#f7b6d2",
"#7f7f7f", "#c7c7c7",
"#bcbd22", "#dbdb8d",
"#17becf", "#9edae5"
];
var d3_category20b = [
"#393b79", "#5254a3", "#6b6ecf", "#9c9ede",
"#637939", "#8ca252", "#b5cf6b", "#cedb9c",
"#8c6d31", "#bd9e39", "#e7ba52", "#e7cb94",
"#843c39", "#ad494a", "#d6616b", "#e7969c",
"#7b4173", "#a55194", "#ce6dbd", "#de9ed6"
];
var d3_category20c = [
"#3182bd", "#6baed6", "#9ecae1", "#c6dbef",
"#e6550d", "#fd8d3c", "#fdae6b", "#fdd0a2",
"#31a354", "#74c476", "#a1d99b", "#c7e9c0",
"#756bb1", "#9e9ac8", "#bcbddc", "#dadaeb",
"#636363", "#969696", "#bdbdbd", "#d9d9d9"
];
d3.scale.quantile = function() {
return d3_scale_quantile([], []);
};
function d3_scale_quantile(domain, range) {
var thresholds;
function rescale() {
var k = 0,
n = domain.length,
q = range.length;
thresholds = [];
while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
return scale;
}
function scale(x) {
if (isNaN(x = +x)) return NaN;
return range[d3.bisect(thresholds, x)];
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.filter(function(d) { return !isNaN(d); }).sort(d3.ascending);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.quantiles = function() {
return thresholds;
};
scale.copy = function() {
return d3_scale_quantile(domain, range); // copy on write!
};
return rescale();
};
d3.scale.quantize = function() {
return d3_scale_quantize(0, 1, [0, 1]);
};
function d3_scale_quantize(x0, x1, range) {
var kx, i;
function scale(x) {
return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
}
function rescale() {
kx = range.length / (x1 - x0);
i = range.length - 1;
return scale;
}
scale.domain = function(x) {
if (!arguments.length) return [x0, x1];
x0 = +x[0];
x1 = +x[x.length - 1];
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.copy = function() {
return d3_scale_quantize(x0, x1, range); // copy on write
};
return rescale();
};
d3.svg = {};
d3.svg.arc = function() {
var innerRadius = d3_svg_arcInnerRadius,
outerRadius = d3_svg_arcOuterRadius,
startAngle = d3_svg_arcStartAngle,
endAngle = d3_svg_arcEndAngle;
function arc() {
var r0 = innerRadius.apply(this, arguments),
r1 = outerRadius.apply(this, arguments),
a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset,
a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset,
da = (a1 < a0 && (da = a0, a0 = a1, a1 = da), a1 - a0),
df = da < Math.PI ? "0" : "1",
c0 = Math.cos(a0),
s0 = Math.sin(a0),
c1 = Math.cos(a1),
s1 = Math.sin(a1);
return da >= d3_svg_arcMax
? (r0
? "M0," + r1
+ "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
+ "A" + r1 + "," + r1 + " 0 1,1 0," + r1
+ "M0," + r0
+ "A" + r0 + "," + r0 + " 0 1,0 0," + (-r0)
+ "A" + r0 + "," + r0 + " 0 1,0 0," + r0
+ "Z"
: "M0," + r1
+ "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
+ "A" + r1 + "," + r1 + " 0 1,1 0," + r1
+ "Z")
: (r0
? "M" + r1 * c0 + "," + r1 * s0
+ "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1
+ "L" + r0 * c1 + "," + r0 * s1
+ "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0
+ "Z"
: "M" + r1 * c0 + "," + r1 * s0
+ "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1
+ "L0,0"
+ "Z");
}
arc.innerRadius = function(v) {
if (!arguments.length) return innerRadius;
innerRadius = d3.functor(v);
return arc;
};
arc.outerRadius = function(v) {
if (!arguments.length) return outerRadius;
outerRadius = d3.functor(v);
return arc;
};
arc.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3.functor(v);
return arc;
};
arc.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3.functor(v);
return arc;
};
arc.centroid = function() {
var r = (innerRadius.apply(this, arguments)
+ outerRadius.apply(this, arguments)) / 2,
a = (startAngle.apply(this, arguments)
+ endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset;
return [Math.cos(a) * r, Math.sin(a) * r];
};
return arc;
};
var d3_svg_arcOffset = -Math.PI / 2,
d3_svg_arcMax = 2 * Math.PI - 1e-6;
function d3_svg_arcInnerRadius(d) {
return d.innerRadius;
}
function d3_svg_arcOuterRadius(d) {
return d.outerRadius;
}
function d3_svg_arcStartAngle(d) {
return d.startAngle;
}
function d3_svg_arcEndAngle(d) {
return d.endAngle;
}
function d3_svg_line(projection) {
var x = d3_svg_lineX,
y = d3_svg_lineY,
interpolate = "linear",
interpolator = d3_svg_lineInterpolators[interpolate],
tension = .7;
function line(d) {
return d.length < 1 ? null : "M" + interpolator(projection(d3_svg_linePoints(this, d, x, y)), tension);
}
line.x = function(v) {
if (!arguments.length) return x;
x = v;
return line;
};
line.y = function(v) {
if (!arguments.length) return y;
y = v;
return line;
};
line.interpolate = function(v) {
if (!arguments.length) return interpolate;
interpolator = d3_svg_lineInterpolators[interpolate = v];
return line;
};
line.tension = function(v) {
if (!arguments.length) return tension;
tension = v;
return line;
};
return line;
}
d3.svg.line = function() {
return d3_svg_line(Object);
};
// Converts the specified array of data into an array of points
// (x-y tuples), by evaluating the specified `x` and `y` functions on each
// data point. The `this` context of the evaluated functions is the specified
// "self" object; each function is passed the current datum and index.
function d3_svg_linePoints(self, d, x, y) {
var points = [],
i = -1,
n = d.length,
fx = typeof x === "function",
fy = typeof y === "function",
value;
if (fx && fy) {
while (++i < n) points.push([
x.call(self, value = d[i], i),
y.call(self, value, i)
]);
} else if (fx) {
while (++i < n) points.push([x.call(self, d[i], i), y]);
} else if (fy) {
while (++i < n) points.push([x, y.call(self, d[i], i)]);
} else {
while (++i < n) points.push([x, y]);
}
return points;
}
// The default `x` property, which references d[0].
function d3_svg_lineX(d) {
return d[0];
}
// The default `y` property, which references d[1].
function d3_svg_lineY(d) {
return d[1];
}
// The various interpolators supported by the `line` class.
var d3_svg_lineInterpolators = {
"linear": d3_svg_lineLinear,
"step-before": d3_svg_lineStepBefore,
"step-after": d3_svg_lineStepAfter,
"basis": d3_svg_lineBasis,
"basis-open": d3_svg_lineBasisOpen,
"basis-closed": d3_svg_lineBasisClosed,
"bundle": d3_svg_lineBundle,
"cardinal": d3_svg_lineCardinal,
"cardinal-open": d3_svg_lineCardinalOpen,
"cardinal-closed": d3_svg_lineCardinalClosed,
"monotone": d3_svg_lineMonotone
};
// Linear interpolation; generates "L" commands.
function d3_svg_lineLinear(points) {
var i = 0,
n = points.length,
p = points[0],
path = [p[0], ",", p[1]];
while (++i < n) path.push("L", (p = points[i])[0], ",", p[1]);
return path.join("");
}
// Step interpolation; generates "H" and "V" commands.
function d3_svg_lineStepBefore(points) {
var i = 0,
n = points.length,
p = points[0],
path = [p[0], ",", p[1]];
while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
return path.join("");
}
// Step interpolation; generates "H" and "V" commands.
function d3_svg_lineStepAfter(points) {
var i = 0,
n = points.length,
p = points[0],
path = [p[0], ",", p[1]];
while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
return path.join("");
}
// Open cardinal spline interpolation; generates "C" commands.
function d3_svg_lineCardinalOpen(points, tension) {
return points.length < 4
? d3_svg_lineLinear(points)
: points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1),
d3_svg_lineCardinalTangents(points, tension));
}
// Closed cardinal spline interpolation; generates "C" commands.
function d3_svg_lineCardinalClosed(points, tension) {
return points.length < 3
? d3_svg_lineLinear(points)
: points[0] + d3_svg_lineHermite((points.push(points[0]), points),
d3_svg_lineCardinalTangents([points[points.length - 2]]
.concat(points, [points[1]]), tension));
}
// Cardinal spline interpolation; generates "C" commands.
function d3_svg_lineCardinal(points, tension, closed) {
return points.length < 3
? d3_svg_lineLinear(points)
: points[0] + d3_svg_lineHermite(points,
d3_svg_lineCardinalTangents(points, tension));
}
// Hermite spline construction; generates "C" commands.
function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1
|| (points.length != tangents.length
&& points.length != tangents.length + 2)) {
return d3_svg_lineLinear(points);
}
var quad = points.length != tangents.length,
path = "",
p0 = points[0],
p = points[1],
t0 = tangents[0],
t = t0,
pi = 1;
if (quad) {
path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3)
+ "," + p[0] + "," + p[1];
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1])
+ "," + (p[0] - t[0]) + "," + (p[1] - t[1])
+ "," + p[0] + "," + p[1];
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1])
+ "," + p[0] + "," + p[1];
}
}
if (quad) {
var lp = points[pi];
path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3)
+ "," + lp[0] + "," + lp[1];
}
return path;
}
// Generates tangents for a cardinal spline.
function d3_svg_lineCardinalTangents(points, tension) {
var tangents = [],
a = (1 - tension) / 2,
p0,
p1 = points[0],
p2 = points[1],
i = 1,
n = points.length;
while (++i < n) {
p0 = p1;
p1 = p2;
p2 = points[i];
tangents.push([a * (p2[0] - p0[0]), a * (p2[1] - p0[1])]);
}
return tangents;
}
// B-spline interpolation; generates "C" commands.
function d3_svg_lineBasis(points) {
if (points.length < 3) return d3_svg_lineLinear(points);
var i = 1,
n = points.length,
pi = points[0],
x0 = pi[0],
y0 = pi[1],
px = [x0, x0, x0, (pi = points[1])[0]],
py = [y0, y0, y0, pi[1]],
path = [x0, ",", y0];
d3_svg_lineBasisBezier(path, px, py);
while (++i < n) {
pi = points[i];
px.shift(); px.push(pi[0]);
py.shift(); py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
i = -1;
while (++i < 2) {
px.shift(); px.push(pi[0]);
py.shift(); py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
// Open B-spline interpolation; generates "C" commands.
function d3_svg_lineBasisOpen(points) {
if (points.length < 4) return d3_svg_lineLinear(points);
var path = [],
i = -1,
n = points.length,
pi,
px = [0],
py = [0];
while (++i < 3) {
pi = points[i];
px.push(pi[0]);
py.push(pi[1]);
}
path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px)
+ "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
--i; while (++i < n) {
pi = points[i];
px.shift(); px.push(pi[0]);
py.shift(); py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
// Closed B-spline interpolation; generates "C" commands.
function d3_svg_lineBasisClosed(points) {
var path,
i = -1,
n = points.length,
m = n + 4,
pi,
px = [],
py = [];
while (++i < 4) {
pi = points[i % n];
px.push(pi[0]);
py.push(pi[1]);
}
path = [
d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",",
d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)
];
--i; while (++i < m) {
pi = points[i % n];
px.shift(); px.push(pi[0]);
py.shift(); py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBundle(points, tension) {
var n = points.length - 1,
x0 = points[0][0],
y0 = points[0][1],
dx = points[n][0] - x0,
dy = points[n][1] - y0,
i = -1,
p,
t;
while (++i <= n) {
p = points[i];
t = i / n;
p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
}
return d3_svg_lineBasis(points);
}
// Returns the dot product of the given four-element vectors.
function d3_svg_lineDot4(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
// Matrix to transform basis (b-spline) control points to bezier
// control points. Derived from FvD 11.2.8.
var d3_svg_lineBasisBezier1 = [0, 2/3, 1/3, 0],
d3_svg_lineBasisBezier2 = [0, 1/3, 2/3, 0],
d3_svg_lineBasisBezier3 = [0, 1/6, 2/3, 1/6];
// Pushes a "C" Bézier curve onto the specified path array, given the
// two specified four-element arrays which define the control points.
function d3_svg_lineBasisBezier(path, x, y) {
path.push(
"C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x),
",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y),
",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x),
",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y),
",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x),
",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
}
// Computes the slope from points p0 to p1.
function d3_svg_lineSlope(p0, p1) {
return (p1[1] - p0[1]) / (p1[0] - p0[0]);
}
// Compute three-point differences for the given points.
// http://en.wikipedia.org/wiki/Cubic_Hermite_spline#Finite_difference
function d3_svg_lineFiniteDifferences(points) {
var i = 0,
j = points.length - 1,
m = [],
p0 = points[0],
p1 = points[1],
d = m[0] = d3_svg_lineSlope(p0, p1);
while (++i < j) {
m[i] = d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]));
}
m[i] = d;
return m;
}
// Interpolates the given points using Fritsch-Carlson Monotone cubic Hermite
// interpolation. Returns an array of tangent vectors. For details, see
// http://en.wikipedia.org/wiki/Monotone_cubic_interpolation
function d3_svg_lineMonotoneTangents(points) {
var tangents = [],
d,
a,
b,
s,
m = d3_svg_lineFiniteDifferences(points),
i = -1,
j = points.length - 1;
// The first two steps are done by computing finite-differences:
// 1. Compute the slopes of the secant lines between successive points.
// 2. Initialize the tangents at every point as the average of the secants.
// Then, for each segment…
while (++i < j) {
d = d3_svg_lineSlope(points[i], points[i + 1]);
// 3. If two successive yk = y{k + 1} are equal (i.e., d is zero), then set
// mk = m{k + 1} = 0 as the spline connecting these points must be flat to
// preserve monotonicity. Ignore step 4 and 5 for those k.
if (Math.abs(d) < 1e-6) {
m[i] = m[i + 1] = 0;
} else {
// 4. Let ak = mk / dk and bk = m{k + 1} / dk.
a = m[i] / d;
b = m[i + 1] / d;
// 5. Prevent overshoot and ensure monotonicity by restricting the
// magnitude of vector <ak, bk> to a circle of radius 3.
s = a * a + b * b;
if (s > 9) {
s = d * 3 / Math.sqrt(s);
m[i] = s * a;
m[i + 1] = s * b;
}
}
}
// Compute the normalized tangent vector from the slopes. Note that if x is
// not monotonic, it's possible that the slope will be infinite, so we protect
// against NaN by setting the coordinate to zero.
i = -1; while (++i <= j) {
s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0])
/ (6 * (1 + m[i] * m[i]));
tangents.push([s || 0, m[i] * s || 0]);
}
return tangents;
}
function d3_svg_lineMonotone(points) {
return points.length < 3
? d3_svg_lineLinear(points)
: points[0] +
d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
}
d3.svg.line.radial = function() {
var line = d3_svg_line(d3_svg_lineRadial);
line.radius = line.x, delete line.x;
line.angle = line.y, delete line.y;
return line;
};
function d3_svg_lineRadial(points) {
var point,
i = -1,
n = points.length,
r,
a;
while (++i < n) {
point = points[i];
r = point[0];
a = point[1] + d3_svg_arcOffset;
point[0] = r * Math.cos(a);
point[1] = r * Math.sin(a);
}
return points;
}
function d3_svg_area(projection) {
var x0 = d3_svg_lineX,
x1 = d3_svg_lineX,
y0 = 0,
y1 = d3_svg_lineY,
interpolate = "linear",
interpolator = d3_svg_lineInterpolators[interpolate],
tension = .7;
function area(d) {
if (d.length < 1) return null;
var points0 = d3_svg_linePoints(this, d, x0, y0),
points1 = d3_svg_linePoints(this, d, x0 === x1 ? d3_svg_areaX(points0) : x1, y0 === y1 ? d3_svg_areaY(points0) : y1);
return "M" + interpolator(projection(points1), tension)
+ "L" + interpolator(projection(points0.reverse()), tension)
+ "Z";
}
area.x = function(x) {
if (!arguments.length) return x1;
x0 = x1 = x;
return area;
};
area.x0 = function(x) {
if (!arguments.length) return x0;
x0 = x;
return area;
};
area.x1 = function(x) {
if (!arguments.length) return x1;
x1 = x;
return area;
};
area.y = function(y) {
if (!arguments.length) return y1;
y0 = y1 = y;
return area;
};
area.y0 = function(y) {
if (!arguments.length) return y0;
y0 = y;
return area;
};
area.y1 = function(y) {
if (!arguments.length) return y1;
y1 = y;
return area;
};
area.interpolate = function(x) {
if (!arguments.length) return interpolate;
interpolator = d3_svg_lineInterpolators[interpolate = x];
return area;
};
area.tension = function(x) {
if (!arguments.length) return tension;
tension = x;
return area;
};
return area;
}
d3.svg.area = function() {
return d3_svg_area(Object);
};
function d3_svg_areaX(points) {
return function(d, i) {
return points[i][0];
};
}
function d3_svg_areaY(points) {
return function(d, i) {
return points[i][1];
};
}
d3.svg.area.radial = function() {
var area = d3_svg_area(d3_svg_lineRadial);
area.radius = area.x, delete area.x;
area.innerRadius = area.x0, delete area.x0;
area.outerRadius = area.x1, delete area.x1;
area.angle = area.y, delete area.y;
area.startAngle = area.y0, delete area.y0;
area.endAngle = area.y1, delete area.y1;
return area;
};
d3.svg.chord = function() {
var source = d3_svg_chordSource,
target = d3_svg_chordTarget,
radius = d3_svg_chordRadius,
startAngle = d3_svg_arcStartAngle,
endAngle = d3_svg_arcEndAngle;
// TODO Allow control point to be customized.
function chord(d, i) {
var s = subgroup(this, source, d, i),
t = subgroup(this, target, d, i);
return "M" + s.p0
+ arc(s.r, s.p1) + (equals(s, t)
? curve(s.r, s.p1, s.r, s.p0)
: curve(s.r, s.p1, t.r, t.p0)
+ arc(t.r, t.p1)
+ curve(t.r, t.p1, s.r, s.p0))
+ "Z";
}
function subgroup(self, f, d, i) {
var subgroup = f.call(self, d, i),
r = radius.call(self, subgroup, i),
a0 = startAngle.call(self, subgroup, i) + d3_svg_arcOffset,
a1 = endAngle.call(self, subgroup, i) + d3_svg_arcOffset;
return {
r: r,
a0: a0,
a1: a1,
p0: [r * Math.cos(a0), r * Math.sin(a0)],
p1: [r * Math.cos(a1), r * Math.sin(a1)]
};
}
function equals(a, b) {
return a.a0 == b.a0 && a.a1 == b.a1;
}
function arc(r, p) {
return "A" + r + "," + r + " 0 0,1 " + p;
}
function curve(r0, p0, r1, p1) {
return "Q 0,0 " + p1;
}
chord.radius = function(v) {
if (!arguments.length) return radius;
radius = d3.functor(v);
return chord;
};
chord.source = function(v) {
if (!arguments.length) return source;
source = d3.functor(v);
return chord;
};
chord.target = function(v) {
if (!arguments.length) return target;
target = d3.functor(v);
return chord;
};
chord.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3.functor(v);
return chord;
};
chord.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3.functor(v);
return chord;
};
return chord;
};
function d3_svg_chordSource(d) {
return d.source;
}
function d3_svg_chordTarget(d) {
return d.target;
}
function d3_svg_chordRadius(d) {
return d.radius;
}
function d3_svg_chordStartAngle(d) {
return d.startAngle;
}
function d3_svg_chordEndAngle(d) {
return d.endAngle;
}
d3.svg.diagonal = function() {
var source = d3_svg_chordSource,
target = d3_svg_chordTarget,
projection = d3_svg_diagonalProjection;
function diagonal(d, i) {
var p0 = source.call(this, d, i),
p3 = target.call(this, d, i),
m = (p0.y + p3.y) / 2,
p = [p0, {x: p0.x, y: m}, {x: p3.x, y: m}, p3];
p = p.map(projection);
return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
}
diagonal.source = function(x) {
if (!arguments.length) return source;
source = d3.functor(x);
return diagonal;
};
diagonal.target = function(x) {
if (!arguments.length) return target;
target = d3.functor(x);
return diagonal;
};
diagonal.projection = function(x) {
if (!arguments.length) return projection;
projection = x;
return diagonal;
};
return diagonal;
};
function d3_svg_diagonalProjection(d) {
return [d.x, d.y];
}
d3.svg.diagonal.radial = function() {
var diagonal = d3.svg.diagonal(),
projection = d3_svg_diagonalProjection,
projection_ = diagonal.projection;
diagonal.projection = function(x) {
return arguments.length
? projection_(d3_svg_diagonalRadialProjection(projection = x))
: projection;
};
return diagonal;
};
function d3_svg_diagonalRadialProjection(projection) {
return function() {
var d = projection.apply(this, arguments),
r = d[0],
a = d[1] + d3_svg_arcOffset;
return [r * Math.cos(a), r * Math.sin(a)];
};
}
d3.svg.mouse = function(container) {
return d3_svg_mousePoint(container, d3.event);
};
// https://bugs.webkit.org/show_bug.cgi?id=44083
var d3_mouse_bug44083 = /WebKit/.test(navigator.userAgent) ? -1 : 0;
function d3_svg_mousePoint(container, e) {
var point = (container.ownerSVGElement || container).createSVGPoint();
if ((d3_mouse_bug44083 < 0) && (window.scrollX || window.scrollY)) {
var svg = d3.select(document.body)
.append("svg:svg")
.style("position", "absolute")
.style("top", 0)
.style("left", 0);
var ctm = svg[0][0].getScreenCTM();
d3_mouse_bug44083 = !(ctm.f || ctm.e);
svg.remove();
}
if (d3_mouse_bug44083) {
point.x = e.pageX;
point.y = e.pageY;
} else {
point.x = e.clientX;
point.y = e.clientY;
}
point = point.matrixTransform(container.getScreenCTM().inverse());
return [point.x, point.y];
};
d3.svg.touches = function(container) {
var touches = d3.event.touches;
return touches ? d3_array(touches).map(function(touch) {
var point = d3_svg_mousePoint(container, touch);
point.identifier = touch.identifier;
return point;
}) : [];
};
d3.svg.symbol = function() {
var type = d3_svg_symbolType,
size = d3_svg_symbolSize;
function symbol(d, i) {
return (d3_svg_symbols[type.call(this, d, i)]
|| d3_svg_symbols.circle)
(size.call(this, d, i));
}
symbol.type = function(x) {
if (!arguments.length) return type;
type = d3.functor(x);
return symbol;
};
// size of symbol in square pixels
symbol.size = function(x) {
if (!arguments.length) return size;
size = d3.functor(x);
return symbol;
};
return symbol;
};
function d3_svg_symbolSize() {
return 64;
}
function d3_svg_symbolType() {
return "circle";
}
// TODO cross-diagonal?
var d3_svg_symbols = {
"circle": function(size) {
var r = Math.sqrt(size / Math.PI);
return "M0," + r
+ "A" + r + "," + r + " 0 1,1 0," + (-r)
+ "A" + r + "," + r + " 0 1,1 0," + r
+ "Z";
},
"cross": function(size) {
var r = Math.sqrt(size / 5) / 2;
return "M" + -3 * r + "," + -r
+ "H" + -r
+ "V" + -3 * r
+ "H" + r
+ "V" + -r
+ "H" + 3 * r
+ "V" + r
+ "H" + r
+ "V" + 3 * r
+ "H" + -r
+ "V" + r
+ "H" + -3 * r
+ "Z";
},
"diamond": function(size) {
var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)),
rx = ry * d3_svg_symbolTan30;
return "M0," + -ry
+ "L" + rx + ",0"
+ " 0," + ry
+ " " + -rx + ",0"
+ "Z";
},
"square": function(size) {
var r = Math.sqrt(size) / 2;
return "M" + -r + "," + -r
+ "L" + r + "," + -r
+ " " + r + "," + r
+ " " + -r + "," + r
+ "Z";
},
"triangle-down": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3),
ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + ry
+ "L" + rx +"," + -ry
+ " " + -rx + "," + -ry
+ "Z";
},
"triangle-up": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3),
ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + -ry
+ "L" + rx +"," + ry
+ " " + -rx + "," + ry
+ "Z";
}
};
d3.svg.symbolTypes = d3.keys(d3_svg_symbols);
var d3_svg_symbolSqrt3 = Math.sqrt(3),
d3_svg_symbolTan30 = Math.tan(30 * Math.PI / 180);
d3.svg.axis = function() {
var scale = d3.scale.linear(),
orient = "bottom",
tickMajorSize = 6,
tickMinorSize = 6,
tickEndSize = 6,
tickPadding = 3,
tickArguments_ = [10],
tickFormat_,
tickSubdivide = 0;
function axis(selection) {
selection.each(function(d, i, j) {
var g = d3.select(this);
// Ticks.
var ticks = scale.ticks.apply(scale, tickArguments_),
tickFormat = tickFormat_ == null ? scale.tickFormat.apply(scale, tickArguments_) : tickFormat_;
// Minor ticks.
var subticks = d3_svg_axisSubdivide(scale, ticks, tickSubdivide),
subtick = g.selectAll(".minor").data(subticks, String),
subtickEnter = subtick.enter().insert("svg:line", "g").attr("class", "tick minor").style("opacity", 1e-6),
subtickExit = transition(subtick.exit()).style("opacity", 1e-6).remove(),
subtickUpdate = transition(subtick).style("opacity", 1);
// Major ticks.
var tick = g.selectAll("g").data(ticks, String),
tickEnter = tick.enter().insert("svg:g", "path").style("opacity", 1e-6),
tickExit = transition(tick.exit()).style("opacity", 1e-6).remove(),
tickUpdate = transition(tick).style("opacity", 1),
tickTransform;
// Domain.
var range = d3_scaleExtent(scale.range()),
path = g.selectAll(".domain").data([0]),
pathEnter = path.enter().append("svg:path").attr("class", "domain"),
pathUpdate = transition(path);
// Stash the new scale and grab the old scale.
var scale0 = this.__chart__ || scale;
this.__chart__ = scale.copy();
tickEnter.append("svg:line").attr("class", "tick");
tickEnter.append("svg:text");
tickUpdate.select("text").text(tickFormat);
switch (orient) {
case "bottom": {
tickTransform = d3_svg_axisX;
subtickUpdate.attr("y2", tickMinorSize);
tickEnter.select("text").attr("dy", ".71em").attr("text-anchor", "middle");
tickUpdate.select("line").attr("y2", tickMajorSize);
tickUpdate.select("text").attr("y", Math.max(tickMajorSize, 0) + tickPadding);
pathUpdate.attr("d", "M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize);
break;
}
case "top": {
tickTransform = d3_svg_axisX;
subtickUpdate.attr("y2", -tickMinorSize);
tickEnter.select("text").attr("text-anchor", "middle");
tickUpdate.select("line").attr("y2", -tickMajorSize);
tickUpdate.select("text").attr("y", -(Math.max(tickMajorSize, 0) + tickPadding));
pathUpdate.attr("d", "M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize);
break;
}
case "left": {
tickTransform = d3_svg_axisY;
subtickUpdate.attr("x2", -tickMinorSize);
tickEnter.select("text").attr("dy", ".32em").attr("text-anchor", "end");
tickUpdate.select("line").attr("x2", -tickMajorSize);
tickUpdate.select("text").attr("x", -(Math.max(tickMajorSize, 0) + tickPadding));
pathUpdate.attr("d", "M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize);
break;
}
case "right": {
tickTransform = d3_svg_axisY;
subtickUpdate.attr("x2", tickMinorSize);
tickEnter.select("text").attr("dy", ".32em");
tickUpdate.select("line").attr("x2", tickMajorSize);
tickUpdate.select("text").attr("x", Math.max(tickMajorSize, 0) + tickPadding);
pathUpdate.attr("d", "M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize);
break;
}
}
tickEnter.call(tickTransform, scale0);
tickUpdate.call(tickTransform, scale);
tickExit.call(tickTransform, scale);
subtickEnter.call(tickTransform, scale0);
subtickUpdate.call(tickTransform, scale);
subtickExit.call(tickTransform, scale);
function transition(o) {
return selection.delay ? o.transition()
.delay(selection[j][i].delay)
.duration(selection[j][i].duration)
.ease(selection.ease()) : o;
}
});
}
axis.scale = function(x) {
if (!arguments.length) return scale;
scale = x;
return axis;
};
axis.orient = function(x) {
if (!arguments.length) return orient;
orient = x;
return axis;
};
axis.ticks = function() {
if (!arguments.length) return tickArguments_;
tickArguments_ = arguments;
return axis;
};
axis.tickFormat = function(x) {
if (!arguments.length) return tickFormat_;
tickFormat_ = x;
return axis;
};
axis.tickSize = function(x, y, z) {
if (!arguments.length) return tickMajorSize;
var n = arguments.length - 1;
tickMajorSize = +x;
tickMinorSize = n > 1 ? +y : tickMajorSize;
tickEndSize = n > 0 ? +arguments[n] : tickMajorSize;
return axis;
};
axis.tickPadding = function(x) {
if (!arguments.length) return tickPadding;
tickPadding = +x;
return axis;
};
axis.tickSubdivide = function(x) {
if (!arguments.length) return tickSubdivide;
tickSubdivide = +x;
return axis;
};
return axis;
};
function d3_svg_axisX(selection, x) {
selection.attr("transform", function(d) { return "translate(" + x(d) + ",0)"; });
}
function d3_svg_axisY(selection, y) {
selection.attr("transform", function(d) { return "translate(0," + y(d) + ")"; });
}
function d3_svg_axisSubdivide(scale, ticks, m) {
subticks = [];
if (m && ticks.length > 1) {
var extent = d3_scaleExtent(scale.domain()),
subticks,
i = -1,
n = ticks.length,
d = (ticks[1] - ticks[0]) / ++m,
j,
v;
while (++i < n) {
for (j = m; --j > 0;) {
if ((v = +ticks[i] - j * d) >= extent[0]) {
subticks.push(v);
}
}
}
for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1];) {
subticks.push(v);
}
}
return subticks;
}
d3.behavior = {};
d3.behavior.drag = function() {
var event = d3.dispatch("drag", "dragstart", "dragend");
function drag() {
this
.on("mousedown.drag", mousedown)
.on("touchstart.drag", mousedown);
d3.select(window)
.on("mousemove.drag", d3_behavior_dragMove)
.on("touchmove.drag", d3_behavior_dragMove)
.on("mouseup.drag", d3_behavior_dragUp, true)
.on("touchend.drag", d3_behavior_dragUp, true)
.on("click.drag", d3_behavior_dragClick, true);
}
// snapshot the local context for subsequent dispatch
function start() {
d3_behavior_dragEvent = event;
d3_behavior_dragEventTarget = d3.event.target;
d3_behavior_dragOffset = d3_behavior_dragPoint((d3_behavior_dragTarget = this).parentNode);
d3_behavior_dragMoved = 0;
d3_behavior_dragArguments = arguments;
}
function mousedown() {
start.apply(this, arguments);
d3_behavior_dragDispatch("dragstart");
}
drag.on = function(type, listener) {
event[type].add(listener);
return drag;
};
return drag;
};
var d3_behavior_dragEvent,
d3_behavior_dragEventTarget,
d3_behavior_dragTarget,
d3_behavior_dragArguments,
d3_behavior_dragOffset,
d3_behavior_dragMoved,
d3_behavior_dragStopClick;
function d3_behavior_dragDispatch(type) {
var o = d3.event, p = d3_behavior_dragTarget.parentNode, dx = 0, dy = 0;
if (p) {
p = d3_behavior_dragPoint(p);
dx = p[0] - d3_behavior_dragOffset[0];
dy = p[1] - d3_behavior_dragOffset[1];
d3_behavior_dragOffset = p;
d3_behavior_dragMoved |= dx | dy;
}
try {
d3.event = {dx: dx, dy: dy};
d3_behavior_dragEvent[type].dispatch.apply(d3_behavior_dragTarget, d3_behavior_dragArguments);
} finally {
d3.event = o;
}
o.preventDefault();
}
function d3_behavior_dragPoint(container) {
return d3.event.touches
? d3.svg.touches(container)[0]
: d3.svg.mouse(container);
}
function d3_behavior_dragMove() {
if (!d3_behavior_dragTarget) return;
var parent = d3_behavior_dragTarget.parentNode;
// O NOES! The drag element was removed from the DOM.
if (!parent) return d3_behavior_dragUp();
d3_behavior_dragDispatch("drag");
d3_behavior_dragCancel();
}
function d3_behavior_dragUp() {
if (!d3_behavior_dragTarget) return;
d3_behavior_dragDispatch("dragend");
d3_behavior_dragTarget = null;
// If the node was moved, prevent the mouseup from propagating.
// Also prevent the subsequent click from propagating (e.g., for anchors).
if (d3_behavior_dragMoved && d3_behavior_dragEventTarget === d3.event.target) {
d3_behavior_dragStopClick = true;
d3_behavior_dragCancel();
}
}
function d3_behavior_dragClick() {
if (d3_behavior_dragStopClick && d3_behavior_dragEventTarget === d3.event.target) {
d3_behavior_dragCancel();
d3_behavior_dragStopClick = false;
d3_behavior_dragEventTarget = null;
}
}
function d3_behavior_dragCancel() {
d3.event.stopPropagation();
d3.event.preventDefault();
}
// TODO unbind zoom behavior?
// TODO unbind listener?
d3.behavior.zoom = function() {
var xyz = [0, 0, 0],
event = d3.dispatch("zoom");
function zoom() {
this
.on("mousedown.zoom", mousedown)
.on("mousewheel.zoom", mousewheel)
.on("DOMMouseScroll.zoom", mousewheel)
.on("dblclick.zoom", dblclick)
.on("touchstart.zoom", touchstart);
d3.select(window)
.on("mousemove.zoom", d3_behavior_zoomMousemove)
.on("mouseup.zoom", d3_behavior_zoomMouseup)
.on("touchmove.zoom", d3_behavior_zoomTouchmove)
.on("touchend.zoom", d3_behavior_zoomTouchup)
.on("click.zoom", d3_behavior_zoomClick, true);
}
// snapshot the local context for subsequent dispatch
function start() {
d3_behavior_zoomXyz = xyz;
d3_behavior_zoomDispatch = event.zoom.dispatch;
d3_behavior_zoomEventTarget = d3.event.target;
d3_behavior_zoomTarget = this;
d3_behavior_zoomArguments = arguments;
}
function mousedown() {
start.apply(this, arguments);
d3_behavior_zoomPanning = d3_behavior_zoomLocation(d3.svg.mouse(d3_behavior_zoomTarget));
d3_behavior_zoomMoved = false;
d3.event.preventDefault();
window.focus();
}
// store starting mouse location
function mousewheel() {
start.apply(this, arguments);
if (!d3_behavior_zoomZooming) d3_behavior_zoomZooming = d3_behavior_zoomLocation(d3.svg.mouse(d3_behavior_zoomTarget));
d3_behavior_zoomTo(d3_behavior_zoomDelta() + xyz[2], d3.svg.mouse(d3_behavior_zoomTarget), d3_behavior_zoomZooming);
}
function dblclick() {
start.apply(this, arguments);
var mouse = d3.svg.mouse(d3_behavior_zoomTarget);
d3_behavior_zoomTo(d3.event.shiftKey ? Math.ceil(xyz[2] - 1) : Math.floor(xyz[2] + 1), mouse, d3_behavior_zoomLocation(mouse));
}
// doubletap detection
function touchstart() {
start.apply(this, arguments);
var touches = d3_behavior_zoomTouchup(),
touch,
now = Date.now();
if ((touches.length === 1) && (now - d3_behavior_zoomLast < 300)) {
d3_behavior_zoomTo(1 + Math.floor(xyz[2]), touch = touches[0], d3_behavior_zoomLocations[touch.identifier]);
}
d3_behavior_zoomLast = now;
}
zoom.on = function(type, listener) {
event[type].add(listener);
return zoom;
};
return zoom;
};
var d3_behavior_zoomDiv,
d3_behavior_zoomPanning,
d3_behavior_zoomZooming,
d3_behavior_zoomLocations = {}, // identifier -> location
d3_behavior_zoomLast = 0,
d3_behavior_zoomXyz,
d3_behavior_zoomDispatch,
d3_behavior_zoomEventTarget,
d3_behavior_zoomTarget,
d3_behavior_zoomArguments,
d3_behavior_zoomMoved,
d3_behavior_zoomStopClick;
function d3_behavior_zoomLocation(point) {
return [
point[0] - d3_behavior_zoomXyz[0],
point[1] - d3_behavior_zoomXyz[1],
d3_behavior_zoomXyz[2]
];
}
// detect the pixels that would be scrolled by this wheel event
function d3_behavior_zoomDelta() {
// mousewheel events are totally broken!
// https://bugs.webkit.org/show_bug.cgi?id=40441
// not only that, but Chrome and Safari differ in re. to acceleration!
if (!d3_behavior_zoomDiv) {
d3_behavior_zoomDiv = d3.select("body").append("div")
.style("visibility", "hidden")
.style("top", 0)
.style("height", 0)
.style("width", 0)
.style("overflow-y", "scroll")
.append("div")
.style("height", "2000px")
.node().parentNode;
}
var e = d3.event, delta;
try {
d3_behavior_zoomDiv.scrollTop = 1000;
d3_behavior_zoomDiv.dispatchEvent(e);
delta = 1000 - d3_behavior_zoomDiv.scrollTop;
} catch (error) {
delta = e.wheelDelta || (-e.detail * 5);
}
return delta * .005;
}
// Note: Since we don't rotate, it's possible for the touches to become
// slightly detached from their original positions. Thus, we recompute the
// touch points on touchend as well as touchstart!
function d3_behavior_zoomTouchup() {
var touches = d3.svg.touches(d3_behavior_zoomTarget),
i = -1,
n = touches.length,
touch;
while (++i < n) d3_behavior_zoomLocations[(touch = touches[i]).identifier] = d3_behavior_zoomLocation(touch);
return touches;
}
function d3_behavior_zoomTouchmove() {
var touches = d3.svg.touches(d3_behavior_zoomTarget);
switch (touches.length) {
// single-touch pan
case 1: {
var touch = touches[0];
d3_behavior_zoomTo(d3_behavior_zoomXyz[2], touch, d3_behavior_zoomLocations[touch.identifier]);
break;
}
// double-touch pan + zoom
case 2: {
var p0 = touches[0],
p1 = touches[1],
p2 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2],
l0 = d3_behavior_zoomLocations[p0.identifier],
l1 = d3_behavior_zoomLocations[p1.identifier],
l2 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2, l0[2]];
d3_behavior_zoomTo(Math.log(d3.event.scale) / Math.LN2 + l0[2], p2, l2);
break;
}
}
}
function d3_behavior_zoomMousemove() {
d3_behavior_zoomZooming = null;
if (d3_behavior_zoomPanning) {
d3_behavior_zoomMoved = true;
d3_behavior_zoomTo(d3_behavior_zoomXyz[2], d3.svg.mouse(d3_behavior_zoomTarget), d3_behavior_zoomPanning);
}
}
function d3_behavior_zoomMouseup() {
if (d3_behavior_zoomPanning) {
if (d3_behavior_zoomMoved && d3_behavior_zoomEventTarget === d3.event.target) {
d3_behavior_zoomStopClick = true;
}
d3_behavior_zoomMousemove();
d3_behavior_zoomPanning = null;
}
}
function d3_behavior_zoomClick() {
if (d3_behavior_zoomStopClick && d3_behavior_zoomEventTarget === d3.event.target) {
d3.event.stopPropagation();
d3.event.preventDefault();
d3_behavior_zoomStopClick = false;
d3_behavior_zoomEventTarget = null;
}
}
function d3_behavior_zoomTo(z, x0, x1) {
var K = Math.pow(2, (d3_behavior_zoomXyz[2] = z) - x1[2]),
x = d3_behavior_zoomXyz[0] = x0[0] - K * x1[0],
y = d3_behavior_zoomXyz[1] = x0[1] - K * x1[1],
o = d3.event, // Events can be reentrant (e.g., focus).
k = Math.pow(2, z);
d3.event = {
scale: k,
translate: [x, y],
transform: function(sx, sy) {
if (sx) transform(sx, x);
if (sy) transform(sy, y);
}
};
function transform(scale, o) {
var domain = scale.__domain || (scale.__domain = scale.domain()),
range = scale.range().map(function(v) { return (v - o) / k; });
scale.domain(domain).domain(range.map(scale.invert));
}
try {
d3_behavior_zoomDispatch.apply(d3_behavior_zoomTarget, d3_behavior_zoomArguments);
} finally {
d3.event = o;
}
o.preventDefault();
}
})();
| mojio/cdnjs | ajax/libs/d3/2.3.2/d3.js | JavaScript | mit | 109,396 |
/*! tether 0.7.1 */
!function(t,e){"function"==typeof define&&define.amd?define(e):"object"==typeof exports?module.exports=e(require,exports,module):t.Tether=e()}(this,function(t,e,o){return function(){var t,e,o,i,n,s,l,r,h,a,f,p,u,d,g,c,m,b,v,y={}.hasOwnProperty,w=[].indexOf||function(t){for(var e=0,o=this.length;o>e;e++)if(e in this&&this[e]===t)return e;return-1},C=[].slice;null==this.Tether&&(this.Tether={modules:[]}),p=function(t){var e,o,i,n,s;if(o=getComputedStyle(t).position,"fixed"===o)return t;for(i=void 0,e=t;e=e.parentNode;){try{n=getComputedStyle(e)}catch(l){}if(null==n)return e;if(/(auto|scroll)/.test(n.overflow+n.overflowY+n.overflowX)&&("absolute"!==o||"relative"===(s=n.position)||"absolute"===s||"fixed"===s))return e}return document.body},m=function(){var t;return t=0,function(){return t++}}(),v={},a=function(t){var e,i,s,l,r;if(s=t._tetherZeroElement,null==s&&(s=t.createElement("div"),s.setAttribute("data-tether-id",m()),n(s.style,{top:0,left:0,position:"absolute"}),t.body.appendChild(s),t._tetherZeroElement=s),e=s.getAttribute("data-tether-id"),null==v[e]){v[e]={},r=s.getBoundingClientRect();for(i in r)l=r[i],v[e][i]=l;o(function(){return v[e]=void 0})}return v[e]},d=null,l=function(t){var e,o,i,n,s,l,r;t===document?(o=document,t=document.documentElement):o=t.ownerDocument,i=o.documentElement,e={},r=t.getBoundingClientRect();for(n in r)l=r[n],e[n]=l;return s=a(o),e.top-=s.top,e.left-=s.left,null==e.width&&(e.width=document.body.scrollWidth-e.left-e.right),null==e.height&&(e.height=document.body.scrollHeight-e.top-e.bottom),e.top=e.top-i.clientTop,e.left=e.left-i.clientLeft,e.right=o.body.clientWidth-e.width-e.left,e.bottom=o.body.clientHeight-e.height-e.top,e},h=function(t){return t.offsetParent||document.documentElement},f=function(){var t,e,o,i,s;return t=document.createElement("div"),t.style.width="100%",t.style.height="200px",e=document.createElement("div"),n(e.style,{position:"absolute",top:0,left:0,pointerEvents:"none",visibility:"hidden",width:"200px",height:"150px",overflow:"hidden"}),e.appendChild(t),document.body.appendChild(e),i=t.offsetWidth,e.style.overflow="scroll",s=t.offsetWidth,i===s&&(s=e.clientWidth),document.body.removeChild(e),o=i-s,{width:o,height:o}},n=function(t){var e,o,i,n,s,l,r;for(null==t&&(t={}),e=[],Array.prototype.push.apply(e,arguments),r=e.slice(1),s=0,l=r.length;l>s;s++)if(i=r[s])for(o in i)y.call(i,o)&&(n=i[o],t[o]=n);return t},g=function(t,e){var o,i,n,s,l,h;if(null!=t.classList){for(l=e.split(" "),h=[],n=0,s=l.length;s>n;n++)i=l[n],i.trim()&&h.push(t.classList.remove(i));return h}return o=r(t).replace(new RegExp("(^| )"+e.split(" ").join("|")+"( |$)","gi")," "),c(t,o)},e=function(t,e){var o,i,n,s,l;if(null!=t.classList){for(s=e.split(" "),l=[],i=0,n=s.length;n>i;i++)o=s[i],o.trim()&&l.push(t.classList.add(o));return l}return g(t,e),o=r(t)+(" "+e),c(t,o)},u=function(t,e){return null!=t.classList?t.classList.contains(e):new RegExp("(^| )"+e+"( |$)","gi").test(r(t))},r=function(t){return t.className instanceof SVGAnimatedString?t.className.baseVal:t.className},c=function(t,e){return t.setAttribute("class",e)},b=function(t,o,i){var n,s,l,r,h,a;for(s=0,r=i.length;r>s;s++)n=i[s],w.call(o,n)<0&&u(t,n)&&g(t,n);for(a=[],l=0,h=o.length;h>l;l++)n=o[l],a.push(u(t,n)?void 0:e(t,n));return a},i=[],o=function(t){return i.push(t)},s=function(){var t,e;for(e=[];t=i.pop();)e.push(t());return e},t=function(){function t(){}return t.prototype.on=function(t,e,o,i){var n;return null==i&&(i=!1),null==this.bindings&&(this.bindings={}),null==(n=this.bindings)[t]&&(n[t]=[]),this.bindings[t].push({handler:e,ctx:o,once:i})},t.prototype.once=function(t,e,o){return this.on(t,e,o,!0)},t.prototype.off=function(t,e){var o,i,n;if(null!=(null!=(i=this.bindings)?i[t]:void 0)){if(null==e)return delete this.bindings[t];for(o=0,n=[];o<this.bindings[t].length;)n.push(this.bindings[t][o].handler===e?this.bindings[t].splice(o,1):o++);return n}},t.prototype.trigger=function(){var t,e,o,i,n,s,l,r,h;if(o=arguments[0],t=2<=arguments.length?C.call(arguments,1):[],null!=(l=this.bindings)?l[o]:void 0){for(n=0,h=[];n<this.bindings[o].length;)r=this.bindings[o][n],i=r.handler,e=r.ctx,s=r.once,i.apply(null!=e?e:this,t),h.push(s?this.bindings[o].splice(n,1):n++);return h}},t}(),this.Tether.Utils={getScrollParent:p,getBounds:l,getOffsetParent:h,extend:n,addClass:e,removeClass:g,hasClass:u,updateClasses:b,defer:o,flush:s,uniqueId:m,Evented:t,getScrollBarSize:f}}.call(this),function(){var t,e,o,i,n,s,l,r,h,a,f,p,u,d,g,c,m,b,v,y,w,C,O,T,x,A,E,S,W,M=[].slice,P=function(t,e){return function(){return t.apply(e,arguments)}};if(null==this.Tether)throw new Error("You must include the utils.js file before tether.js");i=this.Tether,W=i.Utils,c=W.getScrollParent,m=W.getSize,d=W.getOuterSize,p=W.getBounds,u=W.getOffsetParent,a=W.extend,n=W.addClass,O=W.removeClass,A=W.updateClasses,h=W.defer,f=W.flush,g=W.getScrollBarSize,E=function(t,e,o){return null==o&&(o=1),t+o>=e&&e>=t-o},x=function(){var t,e,o,i,n;for(t=document.createElement("div"),n=["transform","webkitTransform","OTransform","MozTransform","msTransform"],o=0,i=n.length;i>o;o++)if(e=n[o],void 0!==t.style[e])return e}(),T=[],C=function(){var t,e,o;for(e=0,o=T.length;o>e;e++)t=T[e],t.position(!1);return f()},b=function(){var t;return null!=(t="undefined"!=typeof performance&&null!==performance&&"function"==typeof performance.now?performance.now():void 0)?t:+new Date},function(){var t,e,o,i,n,s,l,r,h;for(e=null,o=null,i=null,n=function(){if(null!=o&&o>16)return o=Math.min(o-16,250),void(i=setTimeout(n,250));if(!(null!=e&&b()-e<10))return null!=i&&(clearTimeout(i),i=null),e=b(),C(),o=b()-e},r=["resize","scroll","touchmove"],h=[],s=0,l=r.length;l>s;s++)t=r[s],h.push(window.addEventListener(t,n));return h}(),t={center:"center",left:"right",right:"left"},e={middle:"middle",top:"bottom",bottom:"top"},o={top:0,left:0,middle:"50%",center:"50%",bottom:"100%",right:"100%"},r=function(o,i){var n,s;return n=o.left,s=o.top,"auto"===n&&(n=t[i.left]),"auto"===s&&(s=e[i.top]),{left:n,top:s}},l=function(t){var e,i;return{left:null!=(e=o[t.left])?e:t.left,top:null!=(i=o[t.top])?i:t.top}},s=function(){var t,e,o,i,n,s,l;for(e=1<=arguments.length?M.call(arguments,0):[],o={top:0,left:0},n=0,s=e.length;s>n;n++)l=e[n],i=l.top,t=l.left,"string"==typeof i&&(i=parseFloat(i,10)),"string"==typeof t&&(t=parseFloat(t,10)),o.top+=i,o.left+=t;return o},v=function(t,e){return"string"==typeof t.left&&-1!==t.left.indexOf("%")&&(t.left=parseFloat(t.left,10)/100*e.width),"string"==typeof t.top&&-1!==t.top.indexOf("%")&&(t.top=parseFloat(t.top,10)/100*e.height),t},y=w=function(t){var e,o,i;return i=t.split(" "),o=i[0],e=i[1],{top:o,left:e}},S=function(){function t(t){this.position=P(this.position,this);var e,o,n,s,l;for(T.push(this),this.history=[],this.setOptions(t,!1),s=i.modules,o=0,n=s.length;n>o;o++)e=s[o],null!=(l=e.initialize)&&l.call(this);this.position()}return t.modules=[],t.prototype.getClass=function(t){var e,o;return(null!=(e=this.options.classes)?e[t]:void 0)?this.options.classes[t]:(null!=(o=this.options.classes)?o[t]:void 0)!==!1?this.options.classPrefix?""+this.options.classPrefix+"-"+t:t:""},t.prototype.setOptions=function(t,e){var o,i,s,l,r,h;for(this.options=t,null==e&&(e=!0),o={offset:"0 0",targetOffset:"0 0",targetAttachment:"auto auto",classPrefix:"tether"},this.options=a(o,this.options),r=this.options,this.element=r.element,this.target=r.target,this.targetModifier=r.targetModifier,"viewport"===this.target?(this.target=document.body,this.targetModifier="visible"):"scroll-handle"===this.target&&(this.target=document.body,this.targetModifier="scroll-handle"),h=["element","target"],s=0,l=h.length;l>s;s++){if(i=h[s],null==this[i])throw new Error("Tether Error: Both element and target must be defined");null!=this[i].jquery?this[i]=this[i][0]:"string"==typeof this[i]&&(this[i]=document.querySelector(this[i]))}if(n(this.element,this.getClass("element")),this.options.addTargetClasses!==!1&&n(this.target,this.getClass("target")),!this.options.attachment)throw new Error("Tether Error: You must provide an attachment");return this.targetAttachment=y(this.options.targetAttachment),this.attachment=y(this.options.attachment),this.offset=w(this.options.offset),this.targetOffset=w(this.options.targetOffset),null!=this.scrollParent&&this.disable(),"scroll-handle"===this.targetModifier?this.scrollParent=this.target:this.scrollParent=c(this.target),this.options.enabled!==!1?this.enable(e):void 0},t.prototype.getTargetBounds=function(){var t,e,o,i,n,s,l,r,h;if(null==this.targetModifier)return p(this.target);switch(this.targetModifier){case"visible":return this.target===document.body?{top:pageYOffset,left:pageXOffset,height:innerHeight,width:innerWidth}:(t=p(this.target),n={height:t.height,width:t.width,top:t.top,left:t.left},n.height=Math.min(n.height,t.height-(pageYOffset-t.top)),n.height=Math.min(n.height,t.height-(t.top+t.height-(pageYOffset+innerHeight))),n.height=Math.min(innerHeight,n.height),n.height-=2,n.width=Math.min(n.width,t.width-(pageXOffset-t.left)),n.width=Math.min(n.width,t.width-(t.left+t.width-(pageXOffset+innerWidth))),n.width=Math.min(innerWidth,n.width),n.width-=2,n.top<pageYOffset&&(n.top=pageYOffset),n.left<pageXOffset&&(n.left=pageXOffset),n);case"scroll-handle":return h=this.target,h===document.body?(h=document.documentElement,t={left:pageXOffset,top:pageYOffset,height:innerHeight,width:innerWidth}):t=p(h),r=getComputedStyle(h),o=h.scrollWidth>h.clientWidth||"scroll"===[r.overflow,r.overflowX]||this.target!==document.body,s=0,o&&(s=15),i=t.height-parseFloat(r.borderTopWidth)-parseFloat(r.borderBottomWidth)-s,n={width:15,height:.975*i*(i/h.scrollHeight),left:t.left+t.width-parseFloat(r.borderLeftWidth)-15},e=0,408>i&&this.target===document.body&&(e=-11e-5*Math.pow(i,2)-.00727*i+22.58),this.target!==document.body&&(n.height=Math.max(n.height,24)),l=this.target.scrollTop/(h.scrollHeight-i),n.top=l*(i-n.height-e)+t.top+parseFloat(r.borderTopWidth),this.target===document.body&&(n.height=Math.max(n.height,24)),n}},t.prototype.clearCache=function(){return this._cache={}},t.prototype.cache=function(t,e){return null==this._cache&&(this._cache={}),null==this._cache[t]&&(this._cache[t]=e.call(this)),this._cache[t]},t.prototype.enable=function(t){return null==t&&(t=!0),this.options.addTargetClasses!==!1&&n(this.target,this.getClass("enabled")),n(this.element,this.getClass("enabled")),this.enabled=!0,this.scrollParent!==document&&this.scrollParent.addEventListener("scroll",this.position),t?this.position():void 0},t.prototype.disable=function(){return O(this.target,this.getClass("enabled")),O(this.element,this.getClass("enabled")),this.enabled=!1,null!=this.scrollParent?this.scrollParent.removeEventListener("scroll",this.position):void 0},t.prototype.destroy=function(){var t,e,o,i,n;for(this.disable(),n=[],t=o=0,i=T.length;i>o;t=++o){if(e=T[t],e===this){T.splice(t,1);break}n.push(void 0)}return n},t.prototype.updateAttachClasses=function(t,e){var o,i,n,s,l,r,a,f,p,u=this;for(null==t&&(t=this.attachment),null==e&&(e=this.targetAttachment),s=["left","top","bottom","right","middle","center"],(null!=(p=this._addAttachClasses)?p.length:void 0)&&this._addAttachClasses.splice(0,this._addAttachClasses.length),o=null!=this._addAttachClasses?this._addAttachClasses:this._addAttachClasses=[],t.top&&o.push(""+this.getClass("element-attached")+"-"+t.top),t.left&&o.push(""+this.getClass("element-attached")+"-"+t.left),e.top&&o.push(""+this.getClass("target-attached")+"-"+e.top),e.left&&o.push(""+this.getClass("target-attached")+"-"+e.left),i=[],l=0,a=s.length;a>l;l++)n=s[l],i.push(""+this.getClass("element-attached")+"-"+n);for(r=0,f=s.length;f>r;r++)n=s[r],i.push(""+this.getClass("target-attached")+"-"+n);return h(function(){return null!=u._addAttachClasses?(A(u.element,u._addAttachClasses,i),u.options.addTargetClasses!==!1&&A(u.target,u._addAttachClasses,i),u._addAttachClasses=void 0):void 0})},t.prototype.position=function(t){var e,o,n,h,a,d,c,m,b,y,w,C,O,T,x,A,E,S,W,M,P,z,B,_,F,L,Y,H,X,N,j,R,U,q,k,D=this;if(null==t&&(t=!0),this.enabled){for(this.clearCache(),M=r(this.targetAttachment,this.attachment),this.updateAttachClasses(this.attachment,M),e=this.cache("element-bounds",function(){return p(D.element)}),F=e.width,n=e.height,0===F&&0===n&&null!=this.lastSize?(N=this.lastSize,F=N.width,n=N.height):this.lastSize={width:F,height:n},B=z=this.cache("target-bounds",function(){return D.getTargetBounds()}),b=v(l(this.attachment),{width:F,height:n}),P=v(l(M),B),a=v(this.offset,{width:F,height:n}),d=v(this.targetOffset,B),b=s(b,a),P=s(P,d),h=z.left+P.left-b.left,_=z.top+P.top-b.top,j=i.modules,L=0,H=j.length;H>L;L++){if(c=j[L],x=c.position.call(this,{left:h,top:_,targetAttachment:M,targetPos:z,attachment:this.attachment,elementPos:e,offset:b,targetOffset:P,manualOffset:a,manualTargetOffset:d,scrollbarSize:S}),x===!1)return!1;null!=x&&"object"==typeof x&&(_=x.top,h=x.left)}if(m={page:{top:_,left:h},viewport:{top:_-pageYOffset,bottom:pageYOffset-_-n+innerHeight,left:h-pageXOffset,right:pageXOffset-h-F+innerWidth}},document.body.scrollWidth>window.innerWidth&&(S=this.cache("scrollbar-size",g),m.viewport.bottom-=S.height),document.body.scrollHeight>window.innerHeight&&(S=this.cache("scrollbar-size",g),m.viewport.right-=S.width),(""!==(R=document.body.style.position)&&"static"!==R||""!==(U=document.body.parentElement.style.position)&&"static"!==U)&&(m.page.bottom=document.body.scrollHeight-_-n,m.page.right=document.body.scrollWidth-h-F),(null!=(q=this.options.optimizations)?q.moveElement:void 0)!==!1&&null==this.targetModifier){for(w=this.cache("target-offsetparent",function(){return u(D.target)}),T=this.cache("target-offsetparent-bounds",function(){return p(w)}),O=getComputedStyle(w),o=getComputedStyle(this.element),C=T,y={},k=["Top","Left","Bottom","Right"],Y=0,X=k.length;X>Y;Y++)W=k[Y],y[W.toLowerCase()]=parseFloat(O["border"+W+"Width"]);T.right=document.body.scrollWidth-T.left-C.width+y.right,T.bottom=document.body.scrollHeight-T.top-C.height+y.bottom,m.page.top>=T.top+y.top&&m.page.bottom>=T.bottom&&m.page.left>=T.left+y.left&&m.page.right>=T.right&&(E=w.scrollTop,A=w.scrollLeft,m.offset={top:m.page.top-T.top+E-y.top,left:m.page.left-T.left+A-y.left})}return this.move(m),this.history.unshift(m),this.history.length>3&&this.history.pop(),t&&f(),!0}},t.prototype.move=function(t){var e,o,i,n,s,l,r,f,p,d,g,c,m,b,v,y,w,C=this;if(null!=this.element.parentNode){f={};for(d in t){f[d]={};for(n in t[d]){for(i=!1,y=this.history,b=0,v=y.length;v>b;b++)if(r=y[b],!E(null!=(w=r[d])?w[n]:void 0,t[d][n])){i=!0;break}i||(f[d][n]=!0)}}e={top:"",left:"",right:"",bottom:""},p=function(t,o){var i,n,s;return(null!=(s=C.options.optimizations)?s.gpu:void 0)===!1?(t.top?e.top=""+o.top+"px":e.bottom=""+o.bottom+"px",t.left?e.left=""+o.left+"px":e.right=""+o.right+"px"):(t.top?(e.top=0,n=o.top):(e.bottom=0,n=-o.bottom),t.left?(e.left=0,i=o.left):(e.right=0,i=-o.right),e[x]="translateX("+Math.round(i)+"px) translateY("+Math.round(n)+"px)","msTransform"!==x?e[x]+=" translateZ(0)":void 0)},s=!1,(f.page.top||f.page.bottom)&&(f.page.left||f.page.right)?(e.position="absolute",p(f.page,t.page)):(f.viewport.top||f.viewport.bottom)&&(f.viewport.left||f.viewport.right)?(e.position="fixed",p(f.viewport,t.viewport)):null!=f.offset&&f.offset.top&&f.offset.left?(e.position="absolute",l=this.cache("target-offsetparent",function(){return u(C.target)}),u(this.element)!==l&&h(function(){return C.element.parentNode.removeChild(C.element),l.appendChild(C.element)}),p(f.offset,t.offset),s=!0):(e.position="absolute",p({top:!0,left:!0},t.page)),s||"BODY"===this.element.parentNode.tagName||(this.element.parentNode.removeChild(this.element),document.body.appendChild(this.element)),m={},c=!1;for(n in e)g=e[n],o=this.element.style[n],""===o||""===g||"top"!==n&&"left"!==n&&"bottom"!==n&&"right"!==n||(o=parseFloat(o),g=parseFloat(g)),o!==g&&(c=!0,m[n]=e[n]);return c?h(function(){return a(C.element.style,m)}):void 0}},t}(),i.position=C,this.Tether=a(S,i)}.call(this),function(){var t,e,o,i,n,s,l,r,h,a,f=[].indexOf||function(t){for(var e=0,o=this.length;o>e;e++)if(e in this&&this[e]===t)return e;return-1};a=this.Tether.Utils,l=a.getOuterSize,s=a.getBounds,r=a.getSize,i=a.extend,h=a.updateClasses,o=a.defer,e={left:"right",right:"left",top:"bottom",bottom:"top",middle:"middle"},t=["left","top","right","bottom"],n=function(e,o){var i,n,l,r,h,a,f;if("scrollParent"===o?o=e.scrollParent:"window"===o&&(o=[pageXOffset,pageYOffset,innerWidth+pageXOffset,innerHeight+pageYOffset]),o===document&&(o=o.documentElement),null!=o.nodeType)for(n=r=s(o),h=getComputedStyle(o),o=[n.left,n.top,r.width+n.left,r.height+n.top],i=a=0,f=t.length;f>a;i=++a)l=t[i],l=l[0].toUpperCase()+l.substr(1),"Top"===l||"Left"===l?o[i]+=parseFloat(h["border"+l+"Width"]):o[i]-=parseFloat(h["border"+l+"Width"]);return o},this.Tether.modules.push({position:function(e){var l,r,a,p,u,d,g,c,m,b,v,y,w,C,O,T,x,A,E,S,W,M,P,z,B,_,F,L,Y,H,X,N,j,R,U,q,k,D,Z,V,$,G,I,J,K,Q,tt,et=this;if(_=e.top,v=e.left,W=e.targetAttachment,!this.options.constraints)return!0;for(A=function(e){var o,i,n,s;for(et.removeClass(e),s=[],i=0,n=t.length;n>i;i++)o=t[i],s.push(et.removeClass(""+e+"-"+o));return s},V=this.cache("element-bounds",function(){return s(et.element)}),b=V.height,F=V.width,0===F&&0===b&&null!=this.lastSize&&($=this.lastSize,F=$.width,b=$.height),P=this.cache("target-bounds",function(){return et.getTargetBounds()}),M=P.height,z=P.width,S={},m={},r=[this.getClass("pinned"),this.getClass("out-of-bounds")],G=this.options.constraints,L=0,N=G.length;N>L;L++)c=G[L],c.outOfBoundsClass&&r.push(c.outOfBoundsClass),c.pinnedClass&&r.push(c.pinnedClass);for(Y=0,j=r.length;j>Y;Y++)for(g=r[Y],I=["left","top","right","bottom"],H=0,R=I.length;R>H;H++)E=I[H],r.push(""+g+"-"+E);for(l=[],S=i({},W),m=i({},this.attachment),J=this.options.constraints,X=0,U=J.length;U>X;X++){if(c=J[X],B=c.to,a=c.attachment,O=c.pin,null==a&&(a=""),f.call(a," ")>=0?(K=a.split(" "),d=K[0],u=K[1]):u=d=a,p=n(this,B),("target"===d||"both"===d)&&(_<p[1]&&"top"===S.top&&(_+=M,S.top="bottom"),_+b>p[3]&&"bottom"===S.top&&(_-=M,S.top="top")),"together"===d&&(_<p[1]&&"top"===S.top&&("bottom"===m.top?(_+=M,S.top="bottom",_+=b,m.top="top"):"top"===m.top&&(_+=M,S.top="bottom",_-=b,m.top="bottom")),_+b>p[3]&&"bottom"===S.top&&("top"===m.top?(_-=M,S.top="top",_-=b,m.top="bottom"):"bottom"===m.top&&(_-=M,S.top="top",_+=b,m.top="top")),"middle"===S.top&&(_+b>p[3]&&"top"===m.top?(_-=b,m.top="bottom"):_<p[1]&&"bottom"===m.top&&(_+=b,m.top="top"))),("target"===u||"both"===u)&&(v<p[0]&&"left"===S.left&&(v+=z,S.left="right"),v+F>p[2]&&"right"===S.left&&(v-=z,S.left="left")),"together"===u&&(v<p[0]&&"left"===S.left?"right"===m.left?(v+=z,S.left="right",v+=F,m.left="left"):"left"===m.left&&(v+=z,S.left="right",v-=F,m.left="right"):v+F>p[2]&&"right"===S.left?"left"===m.left?(v-=z,S.left="left",v-=F,m.left="right"):"right"===m.left&&(v-=z,S.left="left",v+=F,m.left="left"):"center"===S.left&&(v+F>p[2]&&"left"===m.left?(v-=F,m.left="right"):v<p[0]&&"right"===m.left&&(v+=F,m.left="left"))),("element"===d||"both"===d)&&(_<p[1]&&"bottom"===m.top&&(_+=b,m.top="top"),_+b>p[3]&&"top"===m.top&&(_-=b,m.top="bottom")),("element"===u||"both"===u)&&(v<p[0]&&"right"===m.left&&(v+=F,m.left="left"),v+F>p[2]&&"left"===m.left&&(v-=F,m.left="right")),"string"==typeof O?O=function(){var t,e,o,i;for(o=O.split(","),i=[],e=0,t=o.length;t>e;e++)C=o[e],i.push(C.trim());return i}():O===!0&&(O=["top","left","right","bottom"]),O||(O=[]),T=[],y=[],_<p[1]&&(f.call(O,"top")>=0?(_=p[1],T.push("top")):y.push("top")),_+b>p[3]&&(f.call(O,"bottom")>=0?(_=p[3]-b,T.push("bottom")):y.push("bottom")),v<p[0]&&(f.call(O,"left")>=0?(v=p[0],T.push("left")):y.push("left")),v+F>p[2]&&(f.call(O,"right")>=0?(v=p[2]-F,T.push("right")):y.push("right")),T.length)for(x=null!=(Q=this.options.pinnedClass)?Q:this.getClass("pinned"),l.push(x),D=0,q=T.length;q>D;D++)E=T[D],l.push(""+x+"-"+E);if(y.length)for(w=null!=(tt=this.options.outOfBoundsClass)?tt:this.getClass("out-of-bounds"),l.push(w),Z=0,k=y.length;k>Z;Z++)E=y[Z],l.push(""+w+"-"+E);(f.call(T,"left")>=0||f.call(T,"right")>=0)&&(m.left=S.left=!1),(f.call(T,"top")>=0||f.call(T,"bottom")>=0)&&(m.top=S.top=!1),(S.top!==W.top||S.left!==W.left||m.top!==this.attachment.top||m.left!==this.attachment.left)&&this.updateAttachClasses(m,S)}return o(function(){return et.options.addTargetClasses!==!1&&h(et.target,l,r),h(et.element,l,r)}),{top:_,left:v}}})}.call(this),function(){var t,e,o,i;i=this.Tether.Utils,e=i.getBounds,o=i.updateClasses,t=i.defer,this.Tether.modules.push({position:function(i){var n,s,l,r,h,a,f,p,u,d,g,c,m,b,v,y,w,C,O,T,x,A,E,S,W,M=this;if(g=i.top,a=i.left,x=this.cache("element-bounds",function(){return e(M.element)}),h=x.height,c=x.width,d=this.getTargetBounds(),r=g+h,f=a+c,n=[],g<=d.bottom&&r>=d.top)for(A=["left","right"],m=0,w=A.length;w>m;m++)p=A[m],((E=d[p])===a||E===f)&&n.push(p);if(a<=d.right&&f>=d.left)for(S=["top","bottom"],b=0,C=S.length;C>b;b++)p=S[b],((W=d[p])===g||W===r)&&n.push(p);for(l=[],s=[],u=["left","top","right","bottom"],l.push(this.getClass("abutted")),v=0,O=u.length;O>v;v++)p=u[v],l.push(""+this.getClass("abutted")+"-"+p);for(n.length&&s.push(this.getClass("abutted")),y=0,T=n.length;T>y;y++)p=n[y],s.push(""+this.getClass("abutted")+"-"+p);return t(function(){return M.options.addTargetClasses!==!1&&o(M.target,s,l),o(M.element,s,l)}),!0}})}.call(this),function(){this.Tether.modules.push({position:function(t){var e,o,i,n,s,l,r;return l=t.top,e=t.left,this.options.shift?(o=function(t){return"function"==typeof t?t.call(this,{top:l,left:e}):t},i=o(this.options.shift),"string"==typeof i?(i=i.split(" "),i[1]||(i[1]=i[0]),s=i[0],n=i[1],s=parseFloat(s,10),n=parseFloat(n,10)):(r=[i.top,i.left],s=r[0],n=r[1]),l+=s,e+=n,{top:l,left:e}):void 0}})}.call(this),this.Tether}); | jessepollak/cdnjs | ajax/libs/tether/0.7.1/tether.min.js | JavaScript | mit | 21,828 |
YUI.add('datatable-message', function(Y) {
/**
Adds support for a message container to appear in the table. This can be used
to indicate loading progress, lack of records, or any other communication
needed.
Features added to `Y.DataTable`, and made available for custom classes at
`Y.DataTable.Message`.
@module datatable-message
@class DataTable.Message
@for DataTable
**/
var Message;
Y.namespace('DataTable').Message = Message = function () {};
Message.ATTRS = {
/**
Enables the display of messages in the table. Setting this to false will
prevent the message Node from being created and `showMessage` from doing
anything.
@attribute showMessages
@type {Boolean}
@default true
**/
showMessages: {
value: true,
validator: Y.Lang.isBoolean
}
};
Y.mix(Message.prototype, {
/**
Template used to generate the node that will be used to report messages.
@property MESSAGE_TEMPLATE
@type {HTML}
@default <tbody class="{className}"><td class="{contentClass}" colspan="{colspan}"></td></tbody>
**/
MESSAGE_TEMPLATE: '<tbody class="{className}"><tr><td class="{contentClass}" colspan="{colspan}"></td></tr></tbody>',
/**
Hides the message node.
@method hideMessage
@return {DataTable}
@chainable
**/
hideMessage: function () {
this.get('boundingBox').removeClass(
this.getClassName('message', 'visible'));
return this;
},
/**
Display the message node and set its content to `message`. If there is a
localized `strings` entry for the value of `message`, that string will be
used.
@method showMessage
@param {String} message The message name or message itself to display
@return {DataTable}
@chainable
**/
showMessage: function (message) {
var content = this.getString(message) || message;
if (!this._messageNode) {
this._initMessageNode();
}
if (this.get('showMessages')) {
if (content) {
this._messageNode.one(
'.' + this.getClassName('message', 'content'))
.setContent(content);
this.get('boundingBox').addClass(
this.getClassName('message','visible'));
} else {
// TODO: is this right?
// If no message provided, remove the message node.
this.hideMessage();
}
}
return this;
},
//--------------------------------------------------------------------------
// Protected methods
//--------------------------------------------------------------------------
/**
Updates the colspan of the `<td>` used to display the messages.
@method _afterMessageColumnsChange
@param {EventFacade} e The columnsChange event
@protected
**/
_afterMessageColumnsChange: function (e) {
var contentNode;
if (this._messageNode) {
contentNode = this._messageNode.one(
'.' + this.getClassName('message', 'content'));
if (contentNode) {
contentNode.set('colSpan', this._displayColumns.length);
}
}
},
/**
Relays to `_uiSetMessage` to hide or show the message node.
@method _afterMessageDataChange
@param {EventFacade} e The dataChange event
@protected
**/
_afterMessageDataChange: function (e) {
this._uiSetMessage();
},
/**
Removes the message node if `showMessages` is `false`, or relays to
`_uiSetMessage` if `true`.
@method _afterShowMessagesChange
@param {EventFacade} e The showMessagesChange event
@protected
**/
_afterShowMessagesChange: function (e) {
if (e.newVal) {
this._uiSetMessage(e);
} else if (this._messageNode) {
this.get('boundingBox').removeClass(
this.getClassName('message', 'visible'));
this._messageNode.remove().destroy(true);
this._messageNode = null;
}
},
/**
Binds the events necessary to keep the message node in sync with the current
table and configuration state.
@method _bindMessageUI
@protected
**/
_bindMessageUI: function () {
this.after(['dataChange', '*:add', '*:remove', '*:reset'],
Y.bind('_afterMessageDataChange', this));
this.after('columnsChange', Y.bind('_afterMessageColumnsChange', this));
this.after('showMessagesChange',
Y.bind('_afterShowMessagesChange', this));
},
/**
Merges in the message related strings and hooks into the rendering cycle to
also render and bind the message node.
@method initializer
@protected
**/
initializer: function () {
this._initMessageStrings();
if (this.get('showMessages')) {
this.after('renderBody', Y.bind('_initMessageNode', this));
}
this.after(Y.bind('_bindMessageUI', this), this, 'bindUI');
this.after(Y.bind('_syncMessageUI', this), this, 'syncUI');
},
/**
Creates the `_messageNode` property from the configured `MESSAGE_TEMPLATE`
and inserts it before the `<table>`'s `<tbody>` node.
@method _initMessageNode
@protected
**/
_initMessageNode: function () {
if (!this._messageNode) {
this._messageNode = Y.Node.create(
Y.Lang.sub(this.MESSAGE_TEMPLATE, {
className: this.getClassName('message'),
contentClass: this.getClassName('message', 'content'),
colspan: this._displayColumns.length || 1
}));
this._tableNode.insertBefore(this._messageNode, this._tbodyNode);
}
},
/**
Add the messaging related strings to the `strings` map.
@method _initMessageStrings
@protected
**/
_initMessageStrings: function () {
// Not a valueFn because other class extensions will want to add to it
this.set('strings', Y.mix((this.get('strings') || {}),
Y.Intl.get('datatable-message')));
},
/**
Node used to display messages from `showMessage`.
@property _messageNode
@type {Node}
@value `undefined` (not initially set)
**/
//_messageNode: null,
/**
Synchronizes the message UI with the table state.
@method _syncMessageUI
@protected
**/
_syncMessageUI: function () {
this._uiSetMessage();
},
/**
Calls `hideMessage` or `showMessage` as appropriate based on the presence of
records in the `data` ModelList.
This is called when `data` is reset or records are added or removed. Also,
if the `showMessages` attribute is updated. In either case, if the
triggering event has a `message` property on the EventFacade, it will be
passed to `showMessage` (if appropriate). If no such property is on the
facade, the `emptyMessage` will be used (see the strings).
@method _uiSetMessage
@param {EventFacade} e The columnsChange event
@protected
**/
_uiSetMessage: function (e) {
if (!this.data.size()) {
this.showMessage((e && e.message) || 'emptyMessage');
} else {
this.hideMessage();
}
}
});
if (Y.Lang.isFunction(Y.DataTable)) {
Y.Base.mix(Y.DataTable, [ Message ]);
}
}, '@VERSION@' ,{requires:['datatable-base'], skinnable:true, lang:['en']});
| lobbin/cdnjs | ajax/libs/yui/3.5.0pr3/datatable-message/datatable-message.js | JavaScript | mit | 7,513 |
// Backbone.Syphon, v0.4.1
// Copyright (c)2012 Derick Bailey, Muted Solutions, LLC.
// Distributed under MIT license
// http://github.com/derickbailey/backbone.syphon
Backbone.Syphon=function(a,b,c){var d={};d.ignoredTypes=["button","submit","reset","fieldset"],d.serialize=function(a,d){var g={},j=h(d),k=e(a,j);return c.each(k,function(a){var c=b(a),d=f(c),e=j.keyExtractors.get(d),h=e(c),k=j.inputReaders.get(d),l=k(c),m=j.keyAssignmentValidators.get(d);if(m(c,h,l)){var n=j.keySplitter(h);g=i(g,n,l)}}),g},d.deserialize=function(a,d,g){var i=h(g),k=e(a,i),l=j(i,d);c.each(k,function(a){var c=b(a),d=f(c),e=i.keyExtractors.get(d),g=e(c),h=i.inputWriters.get(d),j=l[g];h(c,j)})};var e=function(a,d){var e=g(a),h=e.elements;return h=c.reject(h,function(a){var e,g=f(a),h=d.keyExtractors.get(g),i=h(b(a)),j=c.include(d.ignoredTypes,g),k=c.include(d.include,i),l=c.include(d.exclude,i);return k?e=!1:d.include?e=!0:e=l||j,e}),h},f=function(a){var c,d=b(a),e=d[0].tagName,f=e;return e.toLowerCase()==="input"&&(c=d.attr("type"),c?f=c:f="text"),f.toLowerCase()},g=function(a){return c.isUndefined(a.$el)&&a.tagName.toLowerCase()==="form"?a:a.$el.is("form")?a.el:a.$("form")[0]},h=function(a){var b=c.clone(a)||{};return b.ignoredTypes=c.clone(d.ignoredTypes),b.inputReaders=b.inputReaders||d.InputReaders,b.inputWriters=b.inputWriters||d.InputWriters,b.keyExtractors=b.keyExtractors||d.KeyExtractors,b.keySplitter=b.keySplitter||d.KeySplitter,b.keyJoiner=b.keyJoiner||d.KeyJoiner,b.keyAssignmentValidators=b.keyAssignmentValidators||d.KeyAssignmentValidators,b},i=function(a,b,d){if(!b)return a;var e=b.shift();return a[e]||(a[e]=c.isArray(e)?[]:{}),b.length===0&&(c.isArray(a[e])?a[e].push(d):a[e]=d),b.length>0&&i(a[e],b,d),a},j=function(a,b,d){var e={};return c.each(b,function(b,f){var g={};d&&(f=a.keyJoiner(d,f)),c.isArray(b)?(f+="[]",g[f]=b):c.isObject(b)?g=j(a,b,f):g[f]=b,c.extend(e,g)}),e};return d}(Backbone,jQuery,_),Backbone.Syphon.TypeRegistry=function(){this.registeredTypes={}},Backbone.Syphon.TypeRegistry.extend=Backbone.Model.extend,_.extend(Backbone.Syphon.TypeRegistry.prototype,{get:function(a){var b=this.registeredTypes[a];return b||(b=this.registeredTypes["default"]),b},register:function(a,b){this.registeredTypes[a]=b},registerDefault:function(a){this.registeredTypes["default"]=a},unregister:function(a){this.registeredTypes[a]&&delete this.registeredTypes[a]}}),Backbone.Syphon.KeyExtractorSet=Backbone.Syphon.TypeRegistry.extend(),Backbone.Syphon.KeyExtractors=new Backbone.Syphon.KeyExtractorSet,Backbone.Syphon.KeyExtractors.registerDefault(function(a){return a.prop("name")}),Backbone.Syphon.InputReaderSet=Backbone.Syphon.TypeRegistry.extend(),Backbone.Syphon.InputReaders=new Backbone.Syphon.InputReaderSet,Backbone.Syphon.InputReaders.registerDefault(function(a){return a.val()}),Backbone.Syphon.InputReaders.register("checkbox",function(a){var b=a.prop("checked");return b}),Backbone.Syphon.InputWriterSet=Backbone.Syphon.TypeRegistry.extend(),Backbone.Syphon.InputWriters=new Backbone.Syphon.InputWriterSet,Backbone.Syphon.InputWriters.registerDefault(function(a,b){a.val(b)}),Backbone.Syphon.InputWriters.register("checkbox",function(a,b){a.prop("checked",b)}),Backbone.Syphon.InputWriters.register("radio",function(a,b){a.prop("checked",a.val()===b)}),Backbone.Syphon.KeyAssignmentValidatorSet=Backbone.Syphon.TypeRegistry.extend(),Backbone.Syphon.KeyAssignmentValidators=new Backbone.Syphon.KeyAssignmentValidatorSet,Backbone.Syphon.KeyAssignmentValidators.registerDefault(function(){return!0}),Backbone.Syphon.KeyAssignmentValidators.register("radio",function(a,b,c){return a.prop("checked")}),Backbone.Syphon.KeySplitter=function(a){var b=a.match(/[^\[\]]+/g);return a.indexOf("[]")===a.length-2&&(lastKey=b.pop(),b.push([lastKey])),b},Backbone.Syphon.KeyJoiner=function(a,b){return a+"["+b+"]"}; | NamPNQ/cdnjs | ajax/libs/backbone.syphon/0.4.1/backbone.syphon.min.js | JavaScript | mit | 3,837 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Debug;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Stopwatch\Stopwatch;
class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
public function testStopwatchSections()
{
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch = new Stopwatch());
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
$events = $stopwatch->getSectionEvents($response->headers->get('X-Debug-Token'));
$this->assertEquals(array(
'__section__',
'kernel.request',
'kernel.controller',
'controller',
'kernel.response',
'kernel.terminate',
), array_keys($events));
}
public function testStopwatchCheckControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted'))
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(false));
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$kernel->handle($request);
}
public function testStopwatchStopControllerOnRequestEvent()
{
$stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
->setMethods(array('isStarted', 'stop', 'stopSection'))
->getMock();
$stopwatch->expects($this->once())
->method('isStarted')
->will($this->returnValue(true));
$stopwatch->expects($this->once())
->method('stop');
$stopwatch->expects($this->once())
->method('stopSection');
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);
$kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
$request = Request::create('/');
$kernel->handle($request);
}
public function testAddListenerNested()
{
$called1 = false;
$called2 = false;
$dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$dispatcher->addListener('my-event', function () use ($dispatcher, &$called1, &$called2) {
$called1 = true;
$dispatcher->addListener('my-event', function () use (&$called2) {
$called2 = true;
});
});
$dispatcher->dispatch('my-event');
$this->assertTrue($called1);
$this->assertFalse($called2);
$dispatcher->dispatch('my-event');
$this->assertTrue($called2);
}
public function testListenerCanRemoveItselfWhenExecuted()
{
$eventDispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
$listener1 = function () use ($eventDispatcher, &$listener1) {
$eventDispatcher->removeListener('foo', $listener1);
};
$eventDispatcher->addListener('foo', $listener1);
$eventDispatcher->addListener('foo', function () {});
$eventDispatcher->dispatch('foo');
$this->assertCount(1, $eventDispatcher->getListeners('foo'), 'expected listener1 to be removed');
}
protected function getHttpKernel($dispatcher, $controller)
{
$resolver = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface');
$resolver->expects($this->once())->method('getController')->will($this->returnValue($controller));
$resolver->expects($this->once())->method('getArguments')->will($this->returnValue(array()));
return new HttpKernel($dispatcher, $resolver);
}
}
| priyankamackwan/taxicab | vendor/symfony/http-kernel/Tests/Debug/TraceableEventDispatcherTest.php | PHP | mit | 4,503 |
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; }
if (!__coverage__['build/node-screen/node-screen.js']) {
__coverage__['build/node-screen/node-screen.js'] = {"path":"build/node-screen/node-screen.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":23},"end":{"line":1,"column":42}}},"2":{"name":"(anonymous_2)","line":55,"loc":{"start":{"line":55,"column":4},"end":{"line":55,"column":19}}},"3":{"name":"(anonymous_3)","line":57,"loc":{"start":{"line":57,"column":20},"end":{"line":57,"column":31}}},"4":{"name":"(anonymous_4)","line":68,"loc":{"start":{"line":68,"column":12},"end":{"line":68,"column":23}}},"5":{"name":"(anonymous_5)","line":73,"loc":{"start":{"line":73,"column":12},"end":{"line":73,"column":26}}},"6":{"name":"(anonymous_6)","line":87,"loc":{"start":{"line":87,"column":12},"end":{"line":87,"column":23}}},"7":{"name":"(anonymous_7)","line":92,"loc":{"start":{"line":92,"column":12},"end":{"line":92,"column":26}}},"8":{"name":"(anonymous_8)","line":173,"loc":{"start":{"line":173,"column":12},"end":{"line":173,"column":23}}},"9":{"name":"(anonymous_9)","line":197,"loc":{"start":{"line":197,"column":12},"end":{"line":197,"column":23}}},"10":{"name":"(anonymous_10)","line":213,"loc":{"start":{"line":213,"column":29},"end":{"line":213,"column":56}}},"11":{"name":"(anonymous_11)","line":229,"loc":{"start":{"line":229,"column":28},"end":{"line":229,"column":60}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":238,"column":59}},"2":{"start":{"line":11,"column":0},"end":{"line":65,"column":2}},"3":{"start":{"line":56,"column":8},"end":{"line":63,"column":10}},"4":{"start":{"line":58,"column":16},"end":{"line":58,"column":65}},"5":{"start":{"line":59,"column":16},"end":{"line":59,"column":54}},"6":{"start":{"line":61,"column":16},"end":{"line":61,"column":53}},"7":{"start":{"line":67,"column":0},"end":{"line":84,"column":2}},"8":{"start":{"line":69,"column":8},"end":{"line":69,"column":43}},"9":{"start":{"line":70,"column":8},"end":{"line":70,"column":81}},"10":{"start":{"line":74,"column":8},"end":{"line":74,"column":43}},"11":{"start":{"line":75,"column":8},"end":{"line":82,"column":9}},"12":{"start":{"line":76,"column":12},"end":{"line":80,"column":13}},"13":{"start":{"line":77,"column":16},"end":{"line":77,"column":38}},"14":{"start":{"line":78,"column":19},"end":{"line":80,"column":13}},"15":{"start":{"line":79,"column":16},"end":{"line":79,"column":74}},"16":{"start":{"line":86,"column":0},"end":{"line":103,"column":2}},"17":{"start":{"line":88,"column":8},"end":{"line":88,"column":43}},"18":{"start":{"line":89,"column":8},"end":{"line":89,"column":79}},"19":{"start":{"line":93,"column":8},"end":{"line":93,"column":43}},"20":{"start":{"line":94,"column":8},"end":{"line":101,"column":9}},"21":{"start":{"line":95,"column":12},"end":{"line":99,"column":13}},"22":{"start":{"line":96,"column":16},"end":{"line":96,"column":37}},"23":{"start":{"line":97,"column":19},"end":{"line":99,"column":13}},"24":{"start":{"line":98,"column":16},"end":{"line":98,"column":74}},"25":{"start":{"line":105,"column":0},"end":{"line":159,"column":3}},"26":{"start":{"line":172,"column":0},"end":{"line":189,"column":2}},"27":{"start":{"line":174,"column":8},"end":{"line":175,"column":19}},"28":{"start":{"line":177,"column":8},"end":{"line":181,"column":9}},"29":{"start":{"line":178,"column":12},"end":{"line":180,"column":13}},"30":{"start":{"line":179,"column":16},"end":{"line":179,"column":44}},"31":{"start":{"line":182,"column":8},"end":{"line":186,"column":9}},"32":{"start":{"line":183,"column":12},"end":{"line":183,"column":48}},"33":{"start":{"line":185,"column":12},"end":{"line":185,"column":40}},"34":{"start":{"line":187,"column":8},"end":{"line":187,"column":22}},"35":{"start":{"line":196,"column":0},"end":{"line":200,"column":2}},"36":{"start":{"line":198,"column":8},"end":{"line":198,"column":61}},"37":{"start":{"line":202,"column":0},"end":{"line":202,"column":47}},"38":{"start":{"line":213,"column":0},"end":{"line":219,"column":2}},"39":{"start":{"line":214,"column":4},"end":{"line":214,"column":40}},"40":{"start":{"line":215,"column":4},"end":{"line":217,"column":5}},"41":{"start":{"line":216,"column":8},"end":{"line":216,"column":41}},"42":{"start":{"line":218,"column":4},"end":{"line":218,"column":52}},"43":{"start":{"line":229,"column":0},"end":{"line":235,"column":2}},"44":{"start":{"line":230,"column":4},"end":{"line":230,"column":40}},"45":{"start":{"line":231,"column":4},"end":{"line":233,"column":5}},"46":{"start":{"line":232,"column":8},"end":{"line":232,"column":41}},"47":{"start":{"line":234,"column":4},"end":{"line":234,"column":56}}},"branchMap":{"1":{"line":70,"type":"cond-expr","locations":[{"start":{"line":70,"column":40},"end":{"line":70,"column":55}},{"start":{"line":70,"column":58},"end":{"line":70,"column":80}}]},"2":{"line":75,"type":"if","locations":[{"start":{"line":75,"column":8},"end":{"line":75,"column":8}},{"start":{"line":75,"column":8},"end":{"line":75,"column":8}}]},"3":{"line":76,"type":"if","locations":[{"start":{"line":76,"column":12},"end":{"line":76,"column":12}},{"start":{"line":76,"column":12},"end":{"line":76,"column":12}}]},"4":{"line":78,"type":"if","locations":[{"start":{"line":78,"column":19},"end":{"line":78,"column":19}},{"start":{"line":78,"column":19},"end":{"line":78,"column":19}}]},"5":{"line":78,"type":"binary-expr","locations":[{"start":{"line":78,"column":23},"end":{"line":78,"column":36}},{"start":{"line":78,"column":40},"end":{"line":78,"column":59}}]},"6":{"line":89,"type":"cond-expr","locations":[{"start":{"line":89,"column":39},"end":{"line":89,"column":53}},{"start":{"line":89,"column":56},"end":{"line":89,"column":78}}]},"7":{"line":94,"type":"if","locations":[{"start":{"line":94,"column":8},"end":{"line":94,"column":8}},{"start":{"line":94,"column":8},"end":{"line":94,"column":8}}]},"8":{"line":95,"type":"if","locations":[{"start":{"line":95,"column":12},"end":{"line":95,"column":12}},{"start":{"line":95,"column":12},"end":{"line":95,"column":12}}]},"9":{"line":97,"type":"if","locations":[{"start":{"line":97,"column":19},"end":{"line":97,"column":19}},{"start":{"line":97,"column":19},"end":{"line":97,"column":19}}]},"10":{"line":97,"type":"binary-expr","locations":[{"start":{"line":97,"column":23},"end":{"line":97,"column":36}},{"start":{"line":97,"column":40},"end":{"line":97,"column":59}}]},"11":{"line":177,"type":"if","locations":[{"start":{"line":177,"column":8},"end":{"line":177,"column":8}},{"start":{"line":177,"column":8},"end":{"line":177,"column":8}}]},"12":{"line":177,"type":"binary-expr","locations":[{"start":{"line":177,"column":12},"end":{"line":177,"column":16}},{"start":{"line":177,"column":20},"end":{"line":177,"column":33}}]},"13":{"line":178,"type":"if","locations":[{"start":{"line":178,"column":12},"end":{"line":178,"column":12}},{"start":{"line":178,"column":12},"end":{"line":178,"column":12}}]},"14":{"line":182,"type":"if","locations":[{"start":{"line":182,"column":8},"end":{"line":182,"column":8}},{"start":{"line":182,"column":8},"end":{"line":182,"column":8}}]},"15":{"line":215,"type":"if","locations":[{"start":{"line":215,"column":4},"end":{"line":215,"column":4}},{"start":{"line":215,"column":4},"end":{"line":215,"column":4}}]},"16":{"line":231,"type":"if","locations":[{"start":{"line":231,"column":4},"end":{"line":231,"column":4}},{"start":{"line":231,"column":4},"end":{"line":231,"column":4}}]}},"code":["(function () { YUI.add('node-screen', function (Y, NAME) {","","/**"," * Extended Node interface for managing regions and screen positioning."," * Adds support for positioning elements and normalizes window size and scroll detection. "," * @module node"," * @submodule node-screen"," */","","// these are all \"safe\" returns, no wrapping required","Y.each(["," /**"," * Returns the inner width of the viewport (exludes scrollbar). "," * @config winWidth"," * @for Node"," * @type {Int}"," */"," 'winWidth',",""," /**"," * Returns the inner height of the viewport (exludes scrollbar). "," * @config winHeight"," * @type {Int}"," */"," 'winHeight',",""," /**"," * Document width "," * @config docWidth"," * @type {Int}"," */"," 'docWidth',",""," /**"," * Document height "," * @config docHeight"," * @type {Int}"," */"," 'docHeight',",""," /**"," * Pixel distance the page has been scrolled horizontally "," * @config docScrollX"," * @type {Int}"," */"," 'docScrollX',",""," /**"," * Pixel distance the page has been scrolled vertically "," * @config docScrollY"," * @type {Int}"," */"," 'docScrollY'"," ],"," function(name) {"," Y.Node.ATTRS[name] = {"," getter: function() {"," var args = Array.prototype.slice.call(arguments);"," args.unshift(Y.Node.getDOMNode(this));",""," return Y.DOM[name].apply(this, args);"," }"," };"," }",");","","Y.Node.ATTRS.scrollLeft = {"," getter: function() {"," var node = Y.Node.getDOMNode(this);"," return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node);"," },",""," setter: function(val) {"," var node = Y.Node.getDOMNode(this);"," if (node) {"," if ('scrollLeft' in node) {"," node.scrollLeft = val;"," } else if (node.document || node.nodeType === 9) {"," Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc"," }"," } else {"," }"," }","};","","Y.Node.ATTRS.scrollTop = {"," getter: function() {"," var node = Y.Node.getDOMNode(this);"," return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node);"," },",""," setter: function(val) {"," var node = Y.Node.getDOMNode(this);"," if (node) {"," if ('scrollTop' in node) {"," node.scrollTop = val;"," } else if (node.document || node.nodeType === 9) {"," Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc"," }"," } else {"," }"," }","};","","Y.Node.importMethod(Y.DOM, [","/**"," * Gets the current position of the node in page coordinates. "," * @method getXY"," * @for Node"," * @return {Array} The XY position of the node","*/"," 'getXY',","","/**"," * Set the position of the node in page coordinates, regardless of how the node is positioned."," * @method setXY"," * @param {Array} xy Contains X & Y values for new position (coordinates are page-based)"," * @chainable"," */"," 'setXY',","","/**"," * Gets the current position of the node in page coordinates. "," * @method getX"," * @return {Int} The X position of the node","*/"," 'getX',","","/**"," * Set the position of the node in page coordinates, regardless of how the node is positioned."," * @method setX"," * @param {Int} x X value for new position (coordinates are page-based)"," * @chainable"," */"," 'setX',","","/**"," * Gets the current position of the node in page coordinates. "," * @method getY"," * @return {Int} The Y position of the node","*/"," 'getY',","","/**"," * Set the position of the node in page coordinates, regardless of how the node is positioned."," * @method setY"," * @param {Int} y Y value for new position (coordinates are page-based)"," * @chainable"," */"," 'setY',","","/**"," * Swaps the XY position of this node with another node. "," * @method swapXY"," * @param {Node | HTMLElement} otherNode The node to swap with."," * @chainable"," */"," 'swapXY'","]);","","/**"," * @module node"," * @submodule node-screen"," */","","/**"," * Returns a region object for the node"," * @config region"," * @for Node"," * @type Node"," */","Y.Node.ATTRS.region = {"," getter: function() {"," var node = this.getDOMNode(),"," region;",""," if (node && !node.tagName) {"," if (node.nodeType === 9) { // document"," node = node.documentElement;"," }"," }"," if (Y.DOM.isWindow(node)) {"," region = Y.DOM.viewportRegion(node);"," } else {"," region = Y.DOM.region(node);"," }"," return region;"," }","};","","/**"," * Returns a region object for the node's viewport"," * @config viewportRegion"," * @type Node"," */","Y.Node.ATTRS.viewportRegion = {"," getter: function() {"," return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));"," }","};","","Y.Node.importMethod(Y.DOM, 'inViewportRegion');","","// these need special treatment to extract 2nd node arg","/**"," * Compares the intersection of the node with another node or region"," * @method intersect"," * @for Node"," * @param {Node|Object} node2 The node or region to compare with."," * @param {Object} altRegion An alternate region to use (rather than this node's)."," * @return {Object} An object representing the intersection of the regions."," */","Y.Node.prototype.intersect = function(node2, altRegion) {"," var node1 = Y.Node.getDOMNode(this);"," if (Y.instanceOf(node2, Y.Node)) { // might be a region object"," node2 = Y.Node.getDOMNode(node2);"," }"," return Y.DOM.intersect(node1, node2, altRegion);","};","","/**"," * Determines whether or not the node is within the giving region."," * @method inRegion"," * @param {Node|Object} node2 The node or region to compare with."," * @param {Boolean} all Whether or not all of the node must be in the region."," * @param {Object} altRegion An alternate region to use (rather than this node's)."," * @return {Boolean} True if in region, false if not."," */","Y.Node.prototype.inRegion = function(node2, all, altRegion) {"," var node1 = Y.Node.getDOMNode(this);"," if (Y.instanceOf(node2, Y.Node)) { // might be a region object"," node2 = Y.Node.getDOMNode(node2);"," }"," return Y.DOM.inRegion(node1, node2, all, altRegion);","};","","","}, '@VERSION@', {\"requires\": [\"dom-screen\", \"node-base\"]});","","}());"]};
}
var __cov_XkqlpMAiAd1S49v_bBnOnQ = __coverage__['build/node-screen/node-screen.js'];
__cov_XkqlpMAiAd1S49v_bBnOnQ.s['1']++;YUI.add('node-screen',function(Y,NAME){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['1']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['2']++;Y.each(['winWidth','winHeight','docWidth','docHeight','docScrollX','docScrollY'],function(name){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['2']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['3']++;Y.Node.ATTRS[name]={getter:function(){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['3']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['4']++;var args=Array.prototype.slice.call(arguments);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['5']++;args.unshift(Y.Node.getDOMNode(this));__cov_XkqlpMAiAd1S49v_bBnOnQ.s['6']++;return Y.DOM[name].apply(this,args);}};});__cov_XkqlpMAiAd1S49v_bBnOnQ.s['7']++;Y.Node.ATTRS.scrollLeft={getter:function(){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['4']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['8']++;var node=Y.Node.getDOMNode(this);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['9']++;return'scrollLeft'in node?(__cov_XkqlpMAiAd1S49v_bBnOnQ.b['1'][0]++,node.scrollLeft):(__cov_XkqlpMAiAd1S49v_bBnOnQ.b['1'][1]++,Y.DOM.docScrollX(node));},setter:function(val){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['5']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['10']++;var node=Y.Node.getDOMNode(this);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['11']++;if(node){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['2'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['12']++;if('scrollLeft'in node){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['3'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['13']++;node.scrollLeft=val;}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['3'][1]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['14']++;if((__cov_XkqlpMAiAd1S49v_bBnOnQ.b['5'][0]++,node.document)||(__cov_XkqlpMAiAd1S49v_bBnOnQ.b['5'][1]++,node.nodeType===9)){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['4'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['15']++;Y.DOM._getWin(node).scrollTo(val,Y.DOM.docScrollY(node));}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['4'][1]++;}}}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['2'][1]++;}}};__cov_XkqlpMAiAd1S49v_bBnOnQ.s['16']++;Y.Node.ATTRS.scrollTop={getter:function(){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['6']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['17']++;var node=Y.Node.getDOMNode(this);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['18']++;return'scrollTop'in node?(__cov_XkqlpMAiAd1S49v_bBnOnQ.b['6'][0]++,node.scrollTop):(__cov_XkqlpMAiAd1S49v_bBnOnQ.b['6'][1]++,Y.DOM.docScrollY(node));},setter:function(val){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['7']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['19']++;var node=Y.Node.getDOMNode(this);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['20']++;if(node){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['7'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['21']++;if('scrollTop'in node){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['8'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['22']++;node.scrollTop=val;}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['8'][1]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['23']++;if((__cov_XkqlpMAiAd1S49v_bBnOnQ.b['10'][0]++,node.document)||(__cov_XkqlpMAiAd1S49v_bBnOnQ.b['10'][1]++,node.nodeType===9)){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['9'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['24']++;Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node),val);}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['9'][1]++;}}}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['7'][1]++;}}};__cov_XkqlpMAiAd1S49v_bBnOnQ.s['25']++;Y.Node.importMethod(Y.DOM,['getXY','setXY','getX','setX','getY','setY','swapXY']);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['26']++;Y.Node.ATTRS.region={getter:function(){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['8']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['27']++;var node=this.getDOMNode(),region;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['28']++;if((__cov_XkqlpMAiAd1S49v_bBnOnQ.b['12'][0]++,node)&&(__cov_XkqlpMAiAd1S49v_bBnOnQ.b['12'][1]++,!node.tagName)){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['11'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['29']++;if(node.nodeType===9){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['13'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['30']++;node=node.documentElement;}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['13'][1]++;}}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['11'][1]++;}__cov_XkqlpMAiAd1S49v_bBnOnQ.s['31']++;if(Y.DOM.isWindow(node)){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['14'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['32']++;region=Y.DOM.viewportRegion(node);}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['14'][1]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['33']++;region=Y.DOM.region(node);}__cov_XkqlpMAiAd1S49v_bBnOnQ.s['34']++;return region;}};__cov_XkqlpMAiAd1S49v_bBnOnQ.s['35']++;Y.Node.ATTRS.viewportRegion={getter:function(){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['9']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['36']++;return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));}};__cov_XkqlpMAiAd1S49v_bBnOnQ.s['37']++;Y.Node.importMethod(Y.DOM,'inViewportRegion');__cov_XkqlpMAiAd1S49v_bBnOnQ.s['38']++;Y.Node.prototype.intersect=function(node2,altRegion){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['10']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['39']++;var node1=Y.Node.getDOMNode(this);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['40']++;if(Y.instanceOf(node2,Y.Node)){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['15'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['41']++;node2=Y.Node.getDOMNode(node2);}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['15'][1]++;}__cov_XkqlpMAiAd1S49v_bBnOnQ.s['42']++;return Y.DOM.intersect(node1,node2,altRegion);};__cov_XkqlpMAiAd1S49v_bBnOnQ.s['43']++;Y.Node.prototype.inRegion=function(node2,all,altRegion){__cov_XkqlpMAiAd1S49v_bBnOnQ.f['11']++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['44']++;var node1=Y.Node.getDOMNode(this);__cov_XkqlpMAiAd1S49v_bBnOnQ.s['45']++;if(Y.instanceOf(node2,Y.Node)){__cov_XkqlpMAiAd1S49v_bBnOnQ.b['16'][0]++;__cov_XkqlpMAiAd1S49v_bBnOnQ.s['46']++;node2=Y.Node.getDOMNode(node2);}else{__cov_XkqlpMAiAd1S49v_bBnOnQ.b['16'][1]++;}__cov_XkqlpMAiAd1S49v_bBnOnQ.s['47']++;return Y.DOM.inRegion(node1,node2,all,altRegion);};},'@VERSION@',{'requires':['dom-screen','node-base']});
| cdnjs/cdnjs | ajax/libs/yui/3.12.0/node-screen/node-screen-coverage.js | JavaScript | mit | 20,400 |
YUI.add('event-resize', function(Y) {
/**
* Adds a window resize event that has its behavior normalized to fire at the
* end of the resize rather than constantly during the resize.
* @module event
* @submodule event-resize
*/
(function() {
var detachHandle,
timerHandle,
CE_NAME = 'window:resize',
handler = function(e) {
if (Y.UA.gecko) {
Y.fire(CE_NAME, e);
} else {
if (timerHandle) {
timerHandle.cancel();
}
timerHandle = Y.later(Y.config.windowResizeDelay || 40, Y, function() {
Y.fire(CE_NAME, e);
});
}
};
/**
* Firefox fires the window resize event once when the resize action
* finishes, other browsers fire the event periodically during the
* resize. This code uses timeout logic to simulate the Firefox
* behavior in other browsers.
* @event windowresize
* @for YUI
*/
Y.Env.evt.plugins.windowresize = {
on: function(type, fn) {
// check for single window listener and add if needed
if (!detachHandle) {
detachHandle = Y.Event._attach(['resize', handler]);
}
var a = Y.Array(arguments, 0, true);
a[0] = CE_NAME;
return Y.on.apply(Y, a);
}
};
})();
}, '@VERSION@' ,{requires:['node-base']});
| rileyjshaw/cdnjs | ajax/libs/yui/3.1.2/event/event-resize-debug.js | JavaScript | mit | 1,344 |
/**
* Dark blue theme for Highcharts JS
* @author Torstein Honsi
*/
Highcharts.theme = {
colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee",
"#55BF3B", "#DF5353", "#7798BF", "#aaeeee"],
chart: {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
stops: [
[0, 'rgb(48, 48, 96)'],
[1, 'rgb(0, 0, 0)']
]
},
borderColor: '#000000',
borderWidth: 2,
className: 'dark-container',
plotBackgroundColor: 'rgba(255, 255, 255, .1)',
plotBorderColor: '#CCCCCC',
plotBorderWidth: 1
},
title: {
style: {
color: '#C0C0C0',
font: 'bold 16px "Trebuchet MS", Verdana, sans-serif'
}
},
subtitle: {
style: {
color: '#666666',
font: 'bold 12px "Trebuchet MS", Verdana, sans-serif'
}
},
xAxis: {
gridLineColor: '#333333',
gridLineWidth: 1,
labels: {
style: {
color: '#A0A0A0'
}
},
lineColor: '#A0A0A0',
tickColor: '#A0A0A0',
title: {
style: {
color: '#CCC',
fontWeight: 'bold',
fontSize: '12px',
fontFamily: 'Trebuchet MS, Verdana, sans-serif'
}
}
},
yAxis: {
gridLineColor: '#333333',
labels: {
style: {
color: '#A0A0A0'
}
},
lineColor: '#A0A0A0',
minorTickInterval: null,
tickColor: '#A0A0A0',
tickWidth: 1,
title: {
style: {
color: '#CCC',
fontWeight: 'bold',
fontSize: '12px',
fontFamily: 'Trebuchet MS, Verdana, sans-serif'
}
}
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.75)',
style: {
color: '#F0F0F0'
}
},
toolbar: {
itemStyle: {
color: 'silver'
}
},
plotOptions: {
line: {
dataLabels: {
color: '#CCC'
},
marker: {
lineColor: '#333'
}
},
spline: {
marker: {
lineColor: '#333'
}
},
scatter: {
marker: {
lineColor: '#333'
}
},
candlestick: {
lineColor: 'white'
}
},
legend: {
itemStyle: {
font: '9pt Trebuchet MS, Verdana, sans-serif',
color: '#A0A0A0'
},
itemHoverStyle: {
color: '#FFF'
},
itemHiddenStyle: {
color: '#444'
}
},
credits: {
style: {
color: '#666'
}
},
labels: {
style: {
color: '#CCC'
}
},
navigation: {
buttonOptions: {
symbolStroke: '#DDDDDD',
hoverSymbolStroke: '#FFFFFF',
theme: {
fill: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0.4, '#606060'],
[0.6, '#333333']
]
},
stroke: '#000000'
}
}
},
// scroll charts
rangeSelector: {
buttonTheme: {
fill: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0.4, '#888'],
[0.6, '#555']
]
},
stroke: '#000000',
style: {
color: '#CCC',
fontWeight: 'bold'
},
states: {
hover: {
fill: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0.4, '#BBB'],
[0.6, '#888']
]
},
stroke: '#000000',
style: {
color: 'white'
}
},
select: {
fill: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0.1, '#000'],
[0.3, '#333']
]
},
stroke: '#000000',
style: {
color: 'yellow'
}
}
}
},
inputStyle: {
backgroundColor: '#333',
color: 'silver'
},
labelStyle: {
color: 'silver'
}
},
navigator: {
handles: {
backgroundColor: '#666',
borderColor: '#AAA'
},
outlineColor: '#CCC',
maskFill: 'rgba(16, 16, 16, 0.5)',
series: {
color: '#7798BF',
lineColor: '#A6C7ED'
}
},
scrollbar: {
barBackgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0.4, '#888'],
[0.6, '#555']
]
},
barBorderColor: '#CCC',
buttonArrowColor: '#CCC',
buttonBackgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0.4, '#888'],
[0.6, '#555']
]
},
buttonBorderColor: '#CCC',
rifleColor: '#FFF',
trackBackgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, '#000'],
[1, '#333']
]
},
trackBorderColor: '#666'
},
// special colors for some of the
legendBackgroundColor: 'rgba(0, 0, 0, 0.5)',
background2: 'rgb(35, 35, 70)',
dataLabelsColor: '#444',
textColor: '#C0C0C0',
maskColor: 'rgba(255,255,255,0.3)'
};
// Apply the theme
var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
| unpete/jsdelivr | files/highcharts/4.1.7/themes/dark-blue.js | JavaScript | mit | 4,336 |
/*!
* Bootstrap v3.3.5 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under the MIT license
*/
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.5",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.5",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.5",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.5",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.5",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),
d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); | beingsagir/play-scala-angularjs-architecture | public/lib/bootstrap/bootstrap-3.3.5/js/bootstrap.min.js | JavaScript | mit | 36,816 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.2.4 or newer
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 1.3.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* MS SQL Utility Class
*
* @package CodeIgniter
* @subpackage Drivers
* @category Database
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
class CI_DB_mssql_utility extends CI_DB_utility {
/**
* List databases statement
*
* @var string
*/
protected $_list_databases = 'EXEC sp_helpdb'; // Can also be: EXEC sp_databases
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $_optimize_table = 'ALTER INDEX all ON %s REORGANIZE';
/**
* Export
*
* @param array $params Preferences
* @return bool
*/
protected function _backup($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsupported_feature');
}
}
/* End of file mssql_utility.php */
/* Location: ./system/database/drivers/mssql/mssql_utility.php */ | panxp/codeigniter-swagger | system/database/drivers/mssql/mssql_utility.php | PHP | mit | 2,564 |
<?php
/**
* built-in Server Shell
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 2.3.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AppShell', 'Console/Command');
/**
* built-in Server Shell
*
* @package Cake.Console.Command
*/
class ServerShell extends AppShell {
/**
* Default ServerHost
*
* @var string
*/
const DEFAULT_HOST = 'localhost';
/**
* Default ListenPort
*
* @var int
*/
const DEFAULT_PORT = 80;
/**
* server host
*
* @var string
*/
protected $_host = null;
/**
* listen port
*
* @var string
*/
protected $_port = null;
/**
* document root
*
* @var string
*/
protected $_documentRoot = null;
/**
* Override initialize of the Shell
*
* @return void
*/
public function initialize() {
$this->_host = static::DEFAULT_HOST;
$this->_port = static::DEFAULT_PORT;
$this->_documentRoot = WWW_ROOT;
}
/**
* Starts up the Shell and displays the welcome message.
* Allows for checking and configuring prior to command or main execution
*
* Override this method if you want to remove the welcome information,
* or otherwise modify the pre-command flow.
*
* @return void
* @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::startup
*/
public function startup() {
if (!empty($this->params['host'])) {
$this->_host = $this->params['host'];
}
if (!empty($this->params['port'])) {
$this->_port = $this->params['port'];
}
if (!empty($this->params['document_root'])) {
$this->_documentRoot = $this->params['document_root'];
}
// for Windows
if (substr($this->_documentRoot, -1, 1) === DIRECTORY_SEPARATOR) {
$this->_documentRoot = substr($this->_documentRoot, 0, strlen($this->_documentRoot) - 1);
}
if (preg_match("/^([a-z]:)[\\\]+(.+)$/i", $this->_documentRoot, $m)) {
$this->_documentRoot = $m[1] . '\\' . $m[2];
}
parent::startup();
}
/**
* Displays a header for the shell
*
* @return void
*/
protected function _welcome() {
$this->out();
$this->out(__d('cake_console', '<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version()));
$this->hr();
$this->out(__d('cake_console', 'App : %s', APP_DIR));
$this->out(__d('cake_console', 'Path: %s', APP));
$this->out(__d('cake_console', 'DocumentRoot: %s', $this->_documentRoot));
$this->hr();
}
/**
* Override main() to handle action
*
* @return void
*/
public function main() {
if (version_compare(PHP_VERSION, '5.4.0') < 0) {
$this->out(__d('cake_console', '<warning>This command is available on %s or above</warning>', 'PHP5.4'));
return;
}
$command = sprintf("php -S %s:%d -t %s %s",
$this->_host,
$this->_port,
escapeshellarg($this->_documentRoot),
escapeshellarg($this->_documentRoot . '/index.php')
);
$port = ($this->_port == static::DEFAULT_PORT) ? '' : ':' . $this->_port;
$this->out(__d('cake_console', 'built-in server is running in http://%s%s/', $this->_host, $port));
system($command);
}
/**
* Gets the option parser instance and configures it.
*
* @return ConsoleOptionParser
*/
public function getOptionParser() {
$parser = parent::getOptionParser();
$parser->description(array(
__d('cake_console', 'PHP Built-in Server for CakePHP'),
__d('cake_console', '<warning>[WARN] Don\'t use this at the production environment</warning>')
))->addOption('host', array(
'short' => 'H',
'help' => __d('cake_console', 'ServerHost')
))->addOption('port', array(
'short' => 'p',
'help' => __d('cake_console', 'ListenPort')
))->addOption('document_root', array(
'short' => 'd',
'help' => __d('cake_console', 'DocumentRoot')
));
return $parser;
}
}
| mixvoip/passmanager | lib/Cake/Console/Command/ServerShell.php | PHP | mit | 4,150 |
/*!-----------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* monaco-css version: 1.3.3(69ad62c9851c1708c61446b6ac2218b99fcdd428)
* Released under the MIT license
* https://github.com/Microsoft/monaco-css/blob/master/LICENSE.md
*-----------------------------------------------------------------------------*/
!function(e){if("object"==typeof module&&"object"==typeof module.exports){var n=e(require,exports);void 0!==n&&(module.exports=n)}else"function"==typeof define&&define.amd&&define("vs/language/css/workerManager",["require","exports"],e)}(function(e,n){function t(e){var n,t,i=new r(function(e,r){n=e,t=r},function(){});return e.then(n,t),i}Object.defineProperty(n,"__esModule",{value:!0});var r=monaco.Promise,i=12e4,o=function(){function e(e){var n=this;this._defaults=e,this._worker=null,this._idleCheckInterval=setInterval(function(){return n._checkIfIdle()},3e4),this._lastUsedTime=0,this._configChangeListener=this._defaults.onDidChange(function(){return n._stopWorker()})}return e.prototype._stopWorker=function(){this._worker&&(this._worker.dispose(),this._worker=null),this._client=null},e.prototype.dispose=function(){clearInterval(this._idleCheckInterval),this._configChangeListener.dispose(),this._stopWorker()},e.prototype._checkIfIdle=function(){if(this._worker){var e=Date.now()-this._lastUsedTime;e>i&&this._stopWorker()}},e.prototype._getClient=function(){return this._lastUsedTime=Date.now(),this._client||(this._worker=monaco.editor.createWebWorker({moduleId:"vs/language/css/cssWorker",label:this._defaults.languageId,createData:{languageSettings:this._defaults.diagnosticsOptions,languageId:this._defaults.languageId}}),this._client=this._worker.getProxy()),this._client},e.prototype.getLanguageServiceWorker=function(){for(var e=this,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i;return t(this._getClient().then(function(e){i=e}).then(function(t){return e._worker.withSyncedResources(n)}).then(function(e){return i}))},e}();n.WorkerManager=o}),function(e){if("object"==typeof module&&"object"==typeof module.exports){var n=e(require,exports);void 0!==n&&(module.exports=n)}else"function"==typeof define&&define.amd&&define("vscode-languageserver-types/main",["require","exports"],e)}(function(e,n){Object.defineProperty(n,"__esModule",{value:!0});var t;!function(e){function n(e,n){return{line:e,character:n}}function t(e){var n=e;return A.defined(n)&&A.number(n.line)&&A.number(n.character)}e.create=n,e.is=t}(t=n.Position||(n.Position={}));var r;!function(e){function n(e,n,r,i){if(A.number(e)&&A.number(n)&&A.number(r)&&A.number(i))return{start:t.create(e,n),end:t.create(r,i)};if(t.is(e)&&t.is(n))return{start:e,end:n};throw new Error("Range#create called with invalid arguments["+e+", "+n+", "+r+", "+i+"]")}function r(e){var n=e;return A.defined(n)&&t.is(n.start)&&t.is(n.end)}e.create=n,e.is=r}(r=n.Range||(n.Range={}));var i;!function(e){function n(e,n){return{uri:e,range:n}}function t(e){var n=e;return A.defined(n)&&r.is(n.range)&&(A.string(n.uri)||A.undefined(n.uri))}e.create=n,e.is=t}(i=n.Location||(n.Location={}));var o;!function(e){e.Error=1,e.Warning=2,e.Information=3,e.Hint=4}(o=n.DiagnosticSeverity||(n.DiagnosticSeverity={}));var a;!function(e){function n(e,n,t,r,i){var o={range:e,message:n};return A.defined(t)&&(o.severity=t),A.defined(r)&&(o.code=r),A.defined(i)&&(o.source=i),o}function t(e){var n=e;return A.defined(n)&&r.is(n.range)&&A.string(n.message)&&(A.number(n.severity)||A.undefined(n.severity))&&(A.number(n.code)||A.string(n.code)||A.undefined(n.code))&&(A.string(n.source)||A.undefined(n.source))}e.create=n,e.is=t}(a=n.Diagnostic||(n.Diagnostic={}));var u;!function(e){function n(e,n){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var i={title:e,command:n};return A.defined(t)&&t.length>0&&(i.arguments=t),i}function t(e){var n=e;return A.defined(n)&&A.string(n.title)&&A.string(n.title)}e.create=n,e.is=t}(u=n.Command||(n.Command={}));var s;!function(e){function n(e,n){return{range:e,newText:n}}function t(e,n){return{range:{start:e,end:e},newText:n}}function r(e){return{range:e,newText:""}}e.replace=n,e.insert=t,e.del=r}(s=n.TextEdit||(n.TextEdit={}));var c;!function(e){function n(e,n){return{textDocument:e,edits:n}}function t(e){var n=e;return A.defined(n)&&g.is(n.textDocument)&&Array.isArray(n.edits)}e.create=n,e.is=t}(c=n.TextDocumentEdit||(n.TextDocumentEdit={}));var d=function(){function e(e){this.edits=e}return e.prototype.insert=function(e,n){this.edits.push(s.insert(e,n))},e.prototype.replace=function(e,n){this.edits.push(s.replace(e,n))},e.prototype["delete"]=function(e){this.edits.push(s.del(e))},e.prototype.add=function(e){this.edits.push(e)},e.prototype.all=function(){return this.edits},e.prototype.clear=function(){this.edits.splice(0,this.edits.length)},e}(),f=function(){function e(e){var n=this;this._textEditChanges=Object.create(null),e&&(this._workspaceEdit=e,e.documentChanges?e.documentChanges.forEach(function(e){var t=new d(e.edits);n._textEditChanges[e.textDocument.uri]=t}):e.changes&&Object.keys(e.changes).forEach(function(t){var r=new d(e.changes[t]);n._textEditChanges[t]=r}))}return Object.defineProperty(e.prototype,"edit",{get:function(){return this._workspaceEdit},enumerable:!0,configurable:!0}),e.prototype.getTextEditChange=function(e){if(g.is(e)){if(this._workspaceEdit||(this._workspaceEdit={documentChanges:[]}),!this._workspaceEdit.documentChanges)throw new Error("Workspace edit is not configured for versioned document changes.");var n=e,t=this._textEditChanges[n.uri];if(!t){var r=[],i={textDocument:n,edits:r};this._workspaceEdit.documentChanges.push(i),t=new d(r),this._textEditChanges[n.uri]=t}return t}if(this._workspaceEdit||(this._workspaceEdit={changes:Object.create(null)}),!this._workspaceEdit.changes)throw new Error("Workspace edit is not configured for normal text edit changes.");var t=this._textEditChanges[e];if(!t){var r=[];this._workspaceEdit.changes[e]=r,t=new d(r),this._textEditChanges[e]=t}return t},e}();n.WorkspaceChange=f;var l;!function(e){function n(e){return{uri:e}}function t(e){var n=e;return A.defined(n)&&A.string(n.uri)}e.create=n,e.is=t}(l=n.TextDocumentIdentifier||(n.TextDocumentIdentifier={}));var g;!function(e){function n(e,n){return{uri:e,version:n}}function t(e){var n=e;return A.defined(n)&&A.string(n.uri)&&A.number(n.version)}e.create=n,e.is=t}(g=n.VersionedTextDocumentIdentifier||(n.VersionedTextDocumentIdentifier={}));var m;!function(e){function n(e,n,t,r){return{uri:e,languageId:n,version:t,text:r}}function t(e){var n=e;return A.defined(n)&&A.string(n.uri)&&A.string(n.languageId)&&A.number(n.version)&&A.string(n.text)}e.create=n,e.is=t}(m=n.TextDocumentItem||(n.TextDocumentItem={}));var p;!function(e){e.Text=1,e.Method=2,e.Function=3,e.Constructor=4,e.Field=5,e.Variable=6,e.Class=7,e.Interface=8,e.Module=9,e.Property=10,e.Unit=11,e.Value=12,e.Enum=13,e.Keyword=14,e.Snippet=15,e.Color=16,e.File=17,e.Reference=18}(p=n.CompletionItemKind||(n.CompletionItemKind={}));var h;!function(e){e.PlainText=1,e.Snippet=2}(h=n.InsertTextFormat||(n.InsertTextFormat={}));var v;!function(e){function n(e){return{label:e}}e.create=n}(v=n.CompletionItem||(n.CompletionItem={}));var y;!function(e){function n(e,n){return{items:e?e:[],isIncomplete:!!n}}e.create=n}(y=n.CompletionList||(n.CompletionList={}));var b;!function(e){function n(e){return e.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}e.fromPlainText=n}(b=n.MarkedString||(n.MarkedString={}));var _;!function(e){function n(e,n){return n?{label:e,documentation:n}:{label:e}}e.create=n}(_=n.ParameterInformation||(n.ParameterInformation={}));var C;!function(e){function n(e,n){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var i={label:e};return A.defined(n)&&(i.documentation=n),A.defined(t)?i.parameters=t:i.parameters=[],i}e.create=n}(C=n.SignatureInformation||(n.SignatureInformation={}));var x;!function(e){e.Text=1,e.Read=2,e.Write=3}(x=n.DocumentHighlightKind||(n.DocumentHighlightKind={}));var I;!function(e){function n(e,n){var t={range:e};return A.number(n)&&(t.kind=n),t}e.create=n}(I=n.DocumentHighlight||(n.DocumentHighlight={}));var w;!function(e){e.File=1,e.Module=2,e.Namespace=3,e.Package=4,e.Class=5,e.Method=6,e.Property=7,e.Field=8,e.Constructor=9,e.Enum=10,e.Interface=11,e.Function=12,e.Variable=13,e.Constant=14,e.String=15,e.Number=16,e.Boolean=17,e.Array=18}(w=n.SymbolKind||(n.SymbolKind={}));var k;!function(e){function n(e,n,t,r,i){var o={name:e,kind:n,location:{uri:r,range:t}};return i&&(o.containerName=i),o}e.create=n}(k=n.SymbolInformation||(n.SymbolInformation={}));var S;!function(e){function n(e){return{diagnostics:e}}function t(e){var n=e;return A.defined(n)&&A.typedArray(n.diagnostics,a.is)}e.create=n,e.is=t}(S=n.CodeActionContext||(n.CodeActionContext={}));var D;!function(e){function n(e,n){var t={range:e};return A.defined(n)&&(t.data=n),t}function t(e){var n=e;return A.defined(n)&&r.is(n.range)&&(A.undefined(n.command)||u.is(n.command))}e.create=n,e.is=t}(D=n.CodeLens||(n.CodeLens={}));var K;!function(e){function n(e,n){return{tabSize:e,insertSpaces:n}}function t(e){var n=e;return A.defined(n)&&A.number(n.tabSize)&&A["boolean"](n.insertSpaces)}e.create=n,e.is=t}(K=n.FormattingOptions||(n.FormattingOptions={}));var T=function(){function e(){}return e}();n.DocumentLink=T,function(e){function n(e,n){return{range:e,target:n}}function t(e){var n=e;return A.defined(n)&&r.is(n.range)&&(A.undefined(n.target)||A.string(n.target))}e.create=n,e.is=t}(T=n.DocumentLink||(n.DocumentLink={})),n.DocumentLink=T,n.EOL=["\n","\r\n","\r"];var E;!function(e){function n(e,n,t,r){return new P(e,n,t,r)}function t(e){var n=e;return!!(A.defined(n)&&A.string(n.uri)&&(A.undefined(n.languageId)||A.string(n.languageId))&&A.number(n.lineCount)&&A.func(n.getText)&&A.func(n.positionAt)&&A.func(n.offsetAt))}e.create=n,e.is=t}(E=n.TextDocument||(n.TextDocument={}));var M;!function(e){e.Manual=1,e.AfterDelay=2,e.FocusOut=3}(M=n.TextDocumentSaveReason||(n.TextDocumentSaveReason={}));var A,P=function(){function e(e,n,t,r){this._uri=e,this._languageId=n,this._version=t,this._content=r,this._lineOffsets=null}return Object.defineProperty(e.prototype,"uri",{get:function(){return this._uri},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"languageId",{get:function(){return this._languageId},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"version",{get:function(){return this._version},enumerable:!0,configurable:!0}),e.prototype.getText=function(){return this._content},e.prototype.update=function(e,n){this._content=e.text,this._version=n,this._lineOffsets=null},e.prototype.getLineOffsets=function(){if(null===this._lineOffsets){for(var e=[],n=this._content,t=!0,r=0;r<n.length;r++){t&&(e.push(r),t=!1);var i=n.charAt(r);t="\r"===i||"\n"===i,"\r"===i&&r+1<n.length&&"\n"===n.charAt(r+1)&&r++}t&&n.length>0&&e.push(n.length),this._lineOffsets=e}return this._lineOffsets},e.prototype.positionAt=function(e){e=Math.max(Math.min(e,this._content.length),0);var n=this.getLineOffsets(),r=0,i=n.length;if(0===i)return t.create(0,e);for(;i>r;){var o=Math.floor((r+i)/2);n[o]>e?i=o:r=o+1}var a=r-1;return t.create(a,e-n[a])},e.prototype.offsetAt=function(e){var n=this.getLineOffsets();if(e.line>=n.length)return this._content.length;if(e.line<0)return 0;var t=n[e.line],r=e.line+1<n.length?n[e.line+1]:this._content.length;return Math.max(Math.min(t+e.character,r),t)},Object.defineProperty(e.prototype,"lineCount",{get:function(){return this.getLineOffsets().length},enumerable:!0,configurable:!0}),e}();!function(e){function n(e){return"undefined"!=typeof e}function t(e){return"undefined"==typeof e}function r(e){return e===!0||e===!1}function i(e){return"[object String]"===s.call(e)}function o(e){return"[object Number]"===s.call(e)}function a(e){return"[object Function]"===s.call(e)}function u(e,n){return Array.isArray(e)&&e.every(n)}var s=Object.prototype.toString;e.defined=n,e.undefined=t,e["boolean"]=r,e.string=i,e.number=o,e.func=a,e.typedArray=u}(A||(A={}))}),define("vscode-languageserver-types",["vscode-languageserver-types/main"],function(e){return e}),function(e){if("object"==typeof module&&"object"==typeof module.exports){var n=e(require,exports);void 0!==n&&(module.exports=n)}else"function"==typeof define&&define.amd&&define("vs/language/css/languageFeatures",["require","exports","vscode-languageserver-types"],e)}(function(e,n){function t(e){switch(e){case g.DiagnosticSeverity.Error:return monaco.Severity.Error;case g.DiagnosticSeverity.Warning:return monaco.Severity.Warning;case g.DiagnosticSeverity.Information:case g.DiagnosticSeverity.Hint:default:return monaco.Severity.Info}}function r(e,n){var r="number"==typeof n.code?String(n.code):n.code;return{severity:t(n.severity),startLineNumber:n.range.start.line+1,startColumn:n.range.start.character+1,endLineNumber:n.range.end.line+1,endColumn:n.range.end.character+1,message:n.message,code:r,source:n.source}}function i(e){return e?{character:e.column-1,line:e.lineNumber-1}:void 0}function o(e){return e?new p(e.start.line+1,e.start.character+1,e.end.line+1,e.end.character+1):void 0}function a(e){var n=monaco.languages.CompletionItemKind;switch(e){case g.CompletionItemKind.Text:return n.Text;case g.CompletionItemKind.Method:return n.Method;case g.CompletionItemKind.Function:return n.Function;case g.CompletionItemKind.Constructor:return n.Constructor;case g.CompletionItemKind.Field:return n.Field;case g.CompletionItemKind.Variable:return n.Variable;case g.CompletionItemKind.Class:return n.Class;case g.CompletionItemKind.Interface:return n.Interface;case g.CompletionItemKind.Module:return n.Module;case g.CompletionItemKind.Property:return n.Property;case g.CompletionItemKind.Unit:return n.Unit;case g.CompletionItemKind.Value:return n.Value;case g.CompletionItemKind.Enum:return n.Enum;case g.CompletionItemKind.Keyword:return n.Keyword;case g.CompletionItemKind.Snippet:return n.Snippet;case g.CompletionItemKind.Color:return n.Color;case g.CompletionItemKind.File:return n.File;case g.CompletionItemKind.Reference:return n.Reference}return n.Property}function u(e){return e?Array.isArray(e)?e:[e]:void 0}function s(e){switch(e){case g.DocumentHighlightKind.Read:return monaco.languages.DocumentHighlightKind.Read;case g.DocumentHighlightKind.Write:return monaco.languages.DocumentHighlightKind.Write;case g.DocumentHighlightKind.Text:return monaco.languages.DocumentHighlightKind.Text}return monaco.languages.DocumentHighlightKind.Text}function c(e){return{uri:m.parse(e.uri),range:o(e.range)}}function d(e){if(e&&e.changes){var n=[];for(var t in e.changes)for(var r=0,i=e.changes[t];r<i.length;r++){var a=i[r];n.push({resource:m.parse(t),range:o(a.range),newText:a.newText})}return{edits:n}}}function f(e){var n=monaco.languages.SymbolKind;switch(e){case g.SymbolKind.File:return n.Array;case g.SymbolKind.Module:return n.Module;case g.SymbolKind.Namespace:return n.Namespace;case g.SymbolKind.Package:return n.Package;case g.SymbolKind.Class:return n.Class;case g.SymbolKind.Method:return n.Method;case g.SymbolKind.Property:return n.Property;case g.SymbolKind.Field:return n.Field;case g.SymbolKind.Constructor:return n.Constructor;case g.SymbolKind.Enum:return n.Enum;case g.SymbolKind.Interface:return n.Interface;case g.SymbolKind.Function:return n.Function;case g.SymbolKind.Variable:return n.Variable;case g.SymbolKind.Constant:return n.Constant;case g.SymbolKind.String:return n.String;case g.SymbolKind.Number:return n.Number;case g.SymbolKind.Boolean:return n.Boolean;case g.SymbolKind.Array:return n.Array}return n.Function}function l(e,n){return e.onCancellationRequested(function(){return n.cancel()}),n}Object.defineProperty(n,"__esModule",{value:!0});var g=e("vscode-languageserver-types"),m=monaco.Uri,p=monaco.Range,h=function(){function e(e,n){var t=this;this._languageId=e,this._worker=n,this._disposables=[],this._listener=Object.create(null);var r=function(e){var n=e.getModeId();if(n===t._languageId){var r;t._listener[e.uri.toString()]=e.onDidChangeContent(function(){clearTimeout(r),r=setTimeout(function(){return t._doValidate(e.uri,n)},500)}),t._doValidate(e.uri,n)}},i=function(e){monaco.editor.setModelMarkers(e,t._languageId,[]);var n=e.uri.toString(),r=t._listener[n];r&&(r.dispose(),delete t._listener[n])};this._disposables.push(monaco.editor.onDidCreateModel(r)),this._disposables.push(monaco.editor.onWillDisposeModel(i)),this._disposables.push(monaco.editor.onDidChangeModelLanguage(function(e){i(e.model),r(e.model)})),this._disposables.push({dispose:function(){for(var e in t._listener)t._listener[e].dispose()}}),monaco.editor.getModels().forEach(r)}return e.prototype.dispose=function(){this._disposables.forEach(function(e){return e&&e.dispose()}),this._disposables=[]},e.prototype._doValidate=function(e,n){this._worker(e).then(function(n){return n.doValidation(e.toString())}).then(function(t){var i=t.map(function(n){return r(e,n)}),o=monaco.editor.getModel(e);o.getModeId()===n&&monaco.editor.setModelMarkers(o,n,i)}).done(void 0,function(e){console.error(e)})},e}();n.DiagnostcsAdapter=h;var v=function(){function e(e){this._worker=e}return Object.defineProperty(e.prototype,"triggerCharacters",{get:function(){return[" ",":"]},enumerable:!0,configurable:!0}),e.prototype.provideCompletionItems=function(e,n,t){var r=(e.getWordUntilPosition(n),e.uri);return l(t,this._worker(r).then(function(e){return e.doComplete(r.toString(),i(n))}).then(function(e){if(e){var n=e.items.map(function(e){var n={label:e.label,insertText:e.insertText,sortText:e.sortText,filterText:e.filterText,documentation:e.documentation,detail:e.detail,kind:a(e.kind)};return e.textEdit&&(n.range=o(e.textEdit.range),n.insertText=e.textEdit.newText),e.insertTextFormat===g.InsertTextFormat.Snippet&&(n.insertText={value:n.insertText}),n});return{isIncomplete:e.isIncomplete,items:n}}}))},e}();n.CompletionAdapter=v;var y=function(){function e(e){this._worker=e}return e.prototype.provideHover=function(e,n,t){var r=e.uri;return l(t,this._worker(r).then(function(e){return e.doHover(r.toString(),i(n))}).then(function(e){return e?{range:o(e.range),contents:u(e.contents)}:void 0}))},e}();n.HoverAdapter=y;var b=function(){function e(e){this._worker=e}return e.prototype.provideDocumentHighlights=function(e,n,t){var r=e.uri;return l(t,this._worker(r).then(function(e){return e.findDocumentHighlights(r.toString(),i(n))}).then(function(e){return e?e.map(function(e){return{range:o(e.range),kind:s(e.kind)}}):void 0}))},e}();n.DocumentHighlightAdapter=b;var _=function(){function e(e){this._worker=e}return e.prototype.provideDefinition=function(e,n,t){var r=e.uri;return l(t,this._worker(r).then(function(e){return e.findDefinition(r.toString(),i(n))}).then(function(e){return e?[c(e)]:void 0}))},e}();n.DefinitionAdapter=_;var C=function(){function e(e){this._worker=e}return e.prototype.provideReferences=function(e,n,t,r){var o=e.uri;return l(r,this._worker(o).then(function(e){return e.findReferences(o.toString(),i(n))}).then(function(e){return e?e.map(c):void 0}))},e}();n.ReferenceAdapter=C;var x=function(){function e(e){this._worker=e}return e.prototype.provideRenameEdits=function(e,n,t,r){var o=e.uri;return l(r,this._worker(o).then(function(e){return e.doRename(o.toString(),i(n),t)}).then(function(e){return d(e)}))},e}();n.RenameAdapter=x;var I=function(){function e(e){this._worker=e}return e.prototype.provideDocumentSymbols=function(e,n){var t=e.uri;return l(n,this._worker(t).then(function(e){return e.findDocumentSymbols(t.toString())}).then(function(e){return e?e.map(function(e){return{name:e.name,containerName:e.containerName,kind:f(e.kind),location:c(e.location)}}):void 0}))},e}();n.DocumentSymbolAdapter=I}),function(e){if("object"==typeof module&&"object"==typeof module.exports){var n=e(require,exports);void 0!==n&&(module.exports=n)}else"function"==typeof define&&define.amd&&define("vs/language/css/cssMode",["require","exports","./workerManager","./languageFeatures"],e)}(function(e,n){function t(e){var n=[],t=new r.WorkerManager(e);n.push(t);var o=function(e){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];return t.getLanguageServiceWorker.apply(t,[e].concat(n))},a=e.languageId;n.push(monaco.languages.registerCompletionItemProvider(a,new i.CompletionAdapter(o))),n.push(monaco.languages.registerHoverProvider(a,new i.HoverAdapter(o))),n.push(monaco.languages.registerDocumentHighlightProvider(a,new i.DocumentHighlightAdapter(o))),n.push(monaco.languages.registerDefinitionProvider(a,new i.DefinitionAdapter(o))),n.push(monaco.languages.registerReferenceProvider(a,new i.ReferenceAdapter(o))),n.push(monaco.languages.registerDocumentSymbolProvider(a,new i.DocumentSymbolAdapter(o))),n.push(monaco.languages.registerRenameProvider(a,new i.RenameAdapter(o))),n.push(new i.DiagnostcsAdapter(a,o))}Object.defineProperty(n,"__esModule",{value:!0});var r=e("./workerManager"),i=e("./languageFeatures");n.setupMode=t}); | wout/cdnjs | ajax/libs/monaco-editor/0.10.1/min/vs/language/css/cssMode.js | JavaScript | mit | 20,983 |
"use strict";angular.module("ngLocale",[],["$provide",function($provide){var PLURAL_CATEGORY={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function getDecimals(n){n=n+"";var i=n.indexOf(".");return i==-1?0:n.length-i-1}function getVF(n,opt_precision){var v=opt_precision;if(undefined===v){v=Math.min(getDecimals(n),3)}var base=Math.pow(10,v);var f=(n*base|0)%base;return{v:v,f:f}}$provide.value("$locale",{DATETIME_FORMATS:{AMPMS:["atm","ptm"],DAY:["dimanĉo","lundo","mardo","merkredo","ĵaŭdo","vendredo","sabato"],ERANAMES:["aK","pK"],ERAS:["aK","pK"],FIRSTDAYOFWEEK:0,MONTH:["januaro","februaro","marto","aprilo","majo","junio","julio","aŭgusto","septembro","oktobro","novembro","decembro"],SHORTDAY:["di","lu","ma","me","ĵa","ve","sa"],SHORTMONTH:["jan","feb","mar","apr","maj","jun","jul","aŭg","sep","okt","nov","dec"],STANDALONEMONTH:["januaro","februaro","marto","aprilo","majo","junio","julio","aŭgusto","septembro","oktobro","novembro","decembro"],WEEKENDRANGE:[5,6],fullDate:"EEEE, d-'a' 'de' MMMM y",longDate:"y-MMMM-dd",medium:"y-MMM-dd HH:mm:ss",mediumDate:"y-MMM-dd",mediumTime:"HH:mm:ss","short":"yy-MM-dd HH:mm",shortDate:"yy-MM-dd",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"$",DECIMAL_SEP:",",GROUP_SEP:" ",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"-¤ ",negSuf:"",posPre:"¤ ",posSuf:""}]},id:"eo-001",pluralCat:function(n,opt_precision){var i=n|0;var vf=getVF(n,opt_precision);if(i==1&&vf.v==0){return PLURAL_CATEGORY.ONE}return PLURAL_CATEGORY.OTHER}})}]); | sajochiu/cdnjs | ajax/libs/angular-i18n/1.4.9/angular-locale_eo-001.min.js | JavaScript | mit | 1,629 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/OldView":27,"../lib/OldView.Bind":26,"../lib/Overview":30,"../lib/Persist":32,"../lib/View":38}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Shared":37}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
// Convert the index object to an array of key val objects
this.keys(this.extractKeys(index));
}
return this.$super.call(this, index);
});
BinaryTree.prototype.extractKeys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return true;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._keys[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use)
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRange(type, key, from, to, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
BinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path(),
indexKeyArr = pathSolver.parseArr(this._index),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":31,"./Shared":37}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.emit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; }
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
return new Path(query.substr(3, query.length - 3)).value(item)[0];
}
return new Path(query).value(item)[0];
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":29,"./Path":31,"./ReactorIO":35,"./Shared":37}],5:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":4,"./Shared":37}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
callback();
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":15,"./Overload":29,"./Shared":37}],7:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":29,"./Shared":37}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
if (callback) { callback(false, true); }
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance.
* @func document
* @memberof Db
* @param {String} documentName The name of the document to create.
* @returns {*}
*/
Db.prototype.document = function (documentName) {
if (documentName) {
// Handle being passed an instance
if (documentName instanceof FdbDocument) {
if (documentName.state() !== 'droppped') {
return documentName;
} else {
documentName = documentName.name();
}
}
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":4,"./Shared":37}],10:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener );
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37,"./View":38}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
}
seriesData.push({
name: seriesName,
data: seriesValues
});
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () { self._changeListener.apply(self, arguments); });
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () { self.drop.apply(self); });
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if(typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy
);
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) { callback(false, true); }
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":29,"./Shared":37}],12:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":31,"./Shared":37}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":31,"./Shared":37}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":37}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":28,"./Shared":37}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":29,"./Serialiser":36}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":29}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) {
return true;
} else if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
}
return -1;
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":29}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":37}],27:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":4,"./CollectionGroup":5,"./Shared":37}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":31,"./Shared":37}],29:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],30:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
delete this._name;
this.emit('drop', this);
if (callback) { callback(false, true); }
}
return true;
};
Db.prototype.overview = function (overviewName) {
if (overviewName) {
// Handle being passed an instance
if (overviewName instanceof Overview) {
return overviewName;
}
this._overview = this._overview || {};
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":4,"./Document":9,"./Shared":37}],31:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":37}],32:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) {
callback(err, data, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) {
callback('Cannot save a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot save a collection with no assigned name!');
}
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) {
callback(err, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
} else {
if (callback) {
callback('Cannot load a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot load a collection with no assigned name!');
}
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Db.prototype.load = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
obj[index].load(loadCallback);
}
}
};
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Db.prototype.save = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
obj[index].save(saveCallback);
}
}
};
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":33,"./PersistCrypto":34,"./Shared":37,"async":39,"localforage":81}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":37,"pako":83}],34:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":37,"crypto-js":48}],35:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":37}],36:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Register our handlers
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],37:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.393',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":29}],38:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (!this._view[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37}],39:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":74}],40:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],41:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":42}],42:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":42}],44:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":42}],45:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":42,"./hmac":47,"./sha1":66}],46:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":41,"./core":42}],47:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":42}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":40,"./cipher-core":41,"./core":42,"./enc-base64":43,"./enc-utf16":44,"./evpkdf":45,"./format-hex":46,"./hmac":47,"./lib-typedarrays":49,"./md5":50,"./mode-cfb":51,"./mode-ctr":53,"./mode-ctr-gladman":52,"./mode-ecb":54,"./mode-ofb":55,"./pad-ansix923":56,"./pad-iso10126":57,"./pad-iso97971":58,"./pad-nopadding":59,"./pad-zeropadding":60,"./pbkdf2":61,"./rabbit":63,"./rabbit-legacy":62,"./rc4":64,"./ripemd160":65,"./sha1":66,"./sha224":67,"./sha256":68,"./sha3":69,"./sha384":70,"./sha512":71,"./tripledes":72,"./x64-core":73}],49:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":42}],50:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":42}],51:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":41,"./core":42}],52:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":41,"./core":42}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":41,"./core":42}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":41,"./core":42}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":41,"./core":42}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":41,"./core":42}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":41,"./core":42}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":41,"./core":42}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":41,"./core":42}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":41,"./core":42}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":42,"./hmac":47,"./sha1":66}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],65:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":42}],66:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":42}],67:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":42,"./sha256":68}],68:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":42}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":42,"./x64-core":73}],70:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":42,"./sha512":71,"./x64-core":73}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":42,"./x64-core":73}],72:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],73:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":42}],74:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],75:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
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')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(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 (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":77}],76:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
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.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":75,"asap":77}],77:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":74}],78:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB ||
this.mozIndexedDB || this.OIndexedDB ||
this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = window.BlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({status: xhr.status, response: xhr.response});
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function(resolve, reject) {
var blob = _createBlob([''], {type: 'image/png'});
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function() {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE],
'readwrite');
var getBlobReq = blobTxn.objectStore(
DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function(e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function(res) {
resolve(!!(res && res.type === 'image/png'));
}, function() {
resolve(false);
}).then(function() {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function() {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function(value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function(e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type});
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function(e) {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// added when support for blob shims was added
openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void(0)) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
var dbInfo;
self.ready().then(function() {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function(blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function(value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function() {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function() {
resolve();
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = asyncStorage;
} else if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":76}],79:[function(_dereq_,module,exports){
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
self._dbInfo = dbInfo;
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
return serializerPromise.then(function(lib) {
serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), i + 1);
if (value !== void(0)) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function(keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function(resolve, reject) {
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.EXPORT) {
module.exports = localStorageWrapper;
} else if (moduleType === ModuleType.DEFINE) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"./../utils/serializer":82,"promise":76}],80:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof(options[i]) !== 'string' ?
options[i].toString() : options[i];
}
}
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
var dbInfoPromise = new Promise(function(resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version),
dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function() {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function(t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName +
' (id INTEGER PRIMARY KEY, key unique, value)', [],
function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
});
});
return serializerPromise.then(function(lib) {
serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName +
' WHERE key = ? LIMIT 1', [key],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = serializer.deserialize(result);
}
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [],
function(t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void(0)) {
resolve(result);
return;
}
}
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('INSERT OR REPLACE INTO ' +
dbInfo.storeName +
' (key, value) VALUES (?, ?)',
[key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName +
' WHERE key = ?', [key],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' +
dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName +
' WHERE id = ? LIMIT 1', [n + 1],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).key : null;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [],
function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.DEFINE) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"./../utils/serializer":82,"promise":76}],81:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports &&
typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [
DriverType.INDEXEDDB,
DriverType.WEBSQL,
DriverType.LOCALSTORAGE
];
var LibraryMethods = [
'clear',
'getItem',
'iterate',
'key',
'keys',
'length',
'removeItem',
'setItem'
];
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function(self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB ||
self.mozIndexedDB || self.OIndexedDB ||
self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function() {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator &&
self.navigator.userAgent &&
/Safari/.test(self.navigator.userAgent) &&
!/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB &&
typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function() {
try {
return (self.localStorage &&
('setItem' in self.localStorage) &&
(self.localStorage.setItem));
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) &&
DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof(options) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " +
'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof(options) === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function(driverObject, callback,
errorCallback) {
var defineDriver = new Promise(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
'Custom driver not compliant; see ' +
'https://mozilla.github.io/localForage/#definedriver'
);
var namingError = new Error(
'Custom driver name already in use: ' + driverObject._driver
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod ||
!driverObject[customDriverMethod] ||
typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function(supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
})['catch'](reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
var driverPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
switch (driverName) {
case self.INDEXEDDB:
resolve(_dereq_('./drivers/indexeddb'));
break;
case self.LOCALSTORAGE:
resolve(_dereq_('./drivers/localstorage'));
break;
case self.WEBSQL:
resolve(_dereq_('./drivers/websql'));
break;
}
} else {
resolve(globalObject[driverName]);
}
});
driverPromise.then(function(driver) {
self._extend(driver);
resolve();
});
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
resolve();
} else {
self._driverSet = Promise.reject(error);
reject(error);
}
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":78,"./drivers/localstorage":79,"./drivers/websql":80,"promise":76}],82:[function(_dereq_,module,exports){
(function() {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder ||
globalObject.MSBlobBuilder ||
globalObject.MozBlobBuilder ||
globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' +
bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ",
value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], {type: blobType});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i+=4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i+1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i+2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i+3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if ((bytes.length % 3) === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = localforageSerializer;
} else if (typeof define === 'function' && define.amd) {
define('localforageSerializer', function() {
return localforageSerializer;
});
} else {
this.localforageSerializer = localforageSerializer;
}
}).call(window);
},{}],83:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":84,"./lib/inflate":85,"./lib/utils/common":86,"./lib/zlib/constants":89}],84:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":86,"./utils/strings":87,"./zlib/deflate.js":91,"./zlib/messages":96,"./zlib/zstream":98}],85:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":86,"./utils/strings":87,"./zlib/constants":89,"./zlib/gzheader":92,"./zlib/inflate.js":94,"./zlib/messages":96,"./zlib/zstream":98}],86:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],87:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":86}],88:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],89:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],90:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],91:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":86,"./adler32":88,"./crc32":90,"./messages":96,"./trees":97}],92:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],93:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],94:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":86,"./adler32":88,"./crc32":90,"./inffast":93,"./inftrees":95}],95:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":86}],96:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],97:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":86}],98:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
| jonobr1/cdnjs | ajax/libs/forerunnerdb/1.3.393/fdb-legacy.js | JavaScript | mit | 909,034 |
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/OldView":27,"../lib/OldView.Bind":26,"../lib/Overview":30,"../lib/Persist":32,"../lib/View":38}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":37}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),!0}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,e){e=e||[],this._left&&this._left.findRange(a,b,c,d,e);var f=this.sortAsc(this._data[b],c),g=this.sortAsc(this._data[b],d);if(!(0!==f&&1!==f||0!==g&&-1!==g))switch(a){case"hash":e.push(this._hash);break;case"data":e.push(this._data);break;default:e.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,e),e},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._index),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":31,"./Shared":37}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),d.mixin(n.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey!==a&&(this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex()),this):this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[p]),q=!0;break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);this.chainSend("remove",{query:a,dataSet:d},b),(!b||b&&!b.noEmit)&&this._onRemove(d),this._onChange(),this.deferEmit("change",{type:"remove",data:d})}return c&&c(!1,d),d},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this;if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H=this._metrics.create("find"),I=this.primaryKey(),J=this,K=!0,L={},M=[],N=[],O=[],P={},Q={},R=function(c){return J._match(c,a,b,"and",P)};if(H.start(),a){if(H.time("analyseQuery"),c=this._analyseQuery(J.decouple(a),b,H),H.time("analyseQuery"),H.data("analysis",c),c.hasJoin&&c.queriesJoin){for(H.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],L[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];H.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(H.data("index.potential",c.indexMatch),H.data("index.used",c.indexMatch[0].index),H.time("indexLookup"),e=c.indexMatch[0].lookup||[],H.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(K=!1)):H.flag("usedIndex",!1),K&&(e&&e.length?(d=e.length,H.time("tableScan: "+d),e=e.filter(R)):(d=this._data.length,H.time("tableScan: "+d),e=this._data.filter(R)),H.time("tableScan: "+d)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(Q.page=b.$page,Q.pages=Math.ceil(e.length/b.$limit),Q.records=e.length,b.$page&&b.$limit>0&&(H.data("cursor",Q),e.splice(0,b.$page*b.$limit))),b.$skip&&(Q.skip=b.$skip,e.splice(0,b.$skip),H.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(Q.limit=b.$limit,e.length=b.$limit,H.data("limit",b.$limit)),b.$decouple&&(H.time("decouple"),e=this.decouple(e),H.time("decouple"),H.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=L[k]?L[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=m[n].query),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=J._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else M.push(e[x])}H.data("flag.join",!0)}if(M.length){for(H.time("removalQueue"),z=0;z<M.length;z++)y=e.indexOf(M[z]),y>-1&&e.splice(y,1);H.time("removalQueue")}if(b.$transform){for(H.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));H.time("transform"),H.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(H.time("transformOut"),e=this.transformOut(e),H.time("transformOut")),H.data("results",e.length)}else e=[];H.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?N.push(z):0===b[z]&&O.push(z));if(H.time("scanFields"),N.length||O.length){for(H.data("flag.limitFields",!0),H.data("limitFields.on",N),H.data("limitFields.off",O),H.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(N.length&&A!==I&&-1===N.indexOf(A)&&delete G[A],O.length&&O.indexOf(A)>-1&&delete G[A])}H.time("limitFields")}if(b.$elemMatch){H.data("flag.elemMatch",!0),H.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(J._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}H.time("projection-elemMatch")}if(b.$elemsMatch){H.data("flag.elemsMatch",!0),H.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)J._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}H.time("projection-elemsMatch")}return H.stop(),e.__fdbOp=H,e.$cursor=Q,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g=this;if("string"==typeof a)return"$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b)[0]:new h(a).value(b)[0];c={};for(f in a)if(a.hasOwnProperty(f))switch(d=typeof a[f],e=a[f],d){case"string":"$$."===e.substr(0,3)?c[f]=new h(e.substr(3,e.length-3)).value(b)[0]:c[f]=e;break;case"object":c[f]=g._resolveDynamicQuery(e,b);break;default:c[f]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=String(c),e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.insertIndexViolation=function(a){
var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":29,"./Path":31,"./ReactorIO":35,"./Shared":37}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":4,"./Shared":37}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":8,"./Metrics.js":15,"./Overload":29,"./Shared":37}],7:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":29,"./Shared":37}],9:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),!0):!1},f.prototype.document=function(a){if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document=this._document||{},this._document[a]=this._document[a]||new g(a).db(this),this._document[a]}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":4,"./Shared":37}],10:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked> All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox"> {^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37,"./View":38}],11:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d){var e,f,g,h,i,j,k=this._collection.distinct(a),l=[],m={categories:[]};for(i=0;i<k.length;i++){for(e=k[i],f={},f[a]=e,h=[],g=this._collection.find(f,{orderBy:d}),j=0;j<g.length;j++)m.categories.push(g[j][b]),h.push(g[j][c]);l.push({name:e,data:h})}return{xAxis:m,series:l}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy);for(a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({
object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":29,"./Shared":37}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(h.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},i.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},i.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},i.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},i.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},i.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=i},{"./BinaryTree":3,"./Path":31,"./Shared":37}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":31,"./Shared":37}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":37}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":28,"./Shared":37}],16:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":29,"./Serialiser":36}],19:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":29}],21:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){for(k in b)if(b.hasOwnProperty(k)){if(f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++){if(i[h]instanceof RegExp&&i[h].test(b))return!0;if(i[h]===b)return!0}return!1}throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(l[k]===b)return!1;return!0}throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0}return-1}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":29}],25:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":37}],27:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,
(void 0===b||b===!0)&&this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./Shared":37}],28:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":31,"./Shared":37}],29:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],30:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this),a&&a(!1,!0)}return!0},e.prototype.overview=function(a){return a?a instanceof h?a:(this._overview=this._overview||{},this._overview[a]=this._overview[a]||new h(a).db(this),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":4,"./Document":9,"./Shared":37}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?this._parseArr(a[e],f,c,d):c.push(f));return c},e.prototype.value=function(a,b){if(void 0!==a&&"object"==typeof a){var c,d,e,f,g,h,i,j=[];for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,h=0;e>h;h++){if(f=f[d[h]],g instanceof Array){for(i=0;i<g.length;i++)j=j.concat(this.value(g,i+"."+d[h]));return j}if(!f||"object"!=typeof f)break;g=f}return[f]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":37}],32:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length):b.foundData=!1,c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"::"+this._name),this._db.persist.drop(this._db._name+"::"+this._name+"::metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"::"+this._name,function(){c._db.persist.drop(c._db._name+"::"+c._name+"::metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"::"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"::"+c._name+"::metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"::"+b._name,function(c,d,e){c?a&&a(c):(d&&b.setData(d),b._db.persist.load(b._db._name+"::"+b._name+"::metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":33,"./PersistCrypto":34,"./Shared":37,async:39,localforage:81}],33:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":37,pako:83}],34:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":37,"crypto-js":48}],35:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":37}],36:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],37:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.371",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":29}],38:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b&&!b.isDropped()&&b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,b._querySettings.options,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,b._querySettings.options,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);return this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(a){return this.isDropped()?!0:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),
(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),b.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return a instanceof l?a:(this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=l},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37}],39:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:74}],40:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],41:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":42}],42:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":42}],44:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":42}],45:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":42,"./hmac":47,"./sha1":66}],46:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":41,"./core":42}],47:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS);
}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":42}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":40,"./cipher-core":41,"./core":42,"./enc-base64":43,"./enc-utf16":44,"./evpkdf":45,"./format-hex":46,"./hmac":47,"./lib-typedarrays":49,"./md5":50,"./mode-cfb":51,"./mode-ctr":53,"./mode-ctr-gladman":52,"./mode-ecb":54,"./mode-ofb":55,"./pad-ansix923":56,"./pad-iso10126":57,"./pad-iso97971":58,"./pad-nopadding":59,"./pad-zeropadding":60,"./pbkdf2":61,"./rabbit":63,"./rabbit-legacy":62,"./rc4":64,"./ripemd160":65,"./sha1":66,"./sha224":67,"./sha256":68,"./sha3":69,"./sha384":70,"./sha512":71,"./tripledes":72,"./x64-core":73}],49:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":42}],50:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":42}],51:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":41,"./core":42}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":41,"./core":42}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":41,"./core":42}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":41,"./core":42}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":41,"./core":42}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":41,"./core":42}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":41,"./core":42}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":41,"./core":42}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":41,"./core":42}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":41,"./core":42}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":42,"./hmac":47,"./sha1":66}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],65:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":42}],66:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":42}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":42,"./sha256":68}],68:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":42}],69:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":42,"./x64-core":73}],70:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":42,"./sha512":71,"./x64-core":73}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);
R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":42,"./x64-core":73}],72:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],73:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":42}],74:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],75:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:77}],76:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":75,asap:77}],77:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:74}],78:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=window.BlobBuilder||window.MSBlobBuilder||window.MozBlobBuilder||window.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function e(a){return new u(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function f(a){return new u(function(b,d){var f=c([""],{type:"image/png"}),g=a.transaction([x],"readwrite");g.objectStore(x).put(f,"key"),g.oncomplete=function(){var c=a.transaction([x],"readwrite"),f=c.objectStore(x).get("key");f.onerror=d,f.onsuccess=function(a){var c=a.target.result,d=URL.createObjectURL(c);e(d).then(function(a){b(!(!a||"image/png"!==a.type))},function(){b(!1)}).then(function(){URL.revokeObjectURL(d)})}}})["catch"](function(){return!1})}function g(a){return"boolean"==typeof w?u.resolve(w):f(a).then(function(a){return w=a})}function h(a){return new u(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function i(a){var b=d(atob(a.data));return c([b],{type:a.type})}function j(a){return a&&a.__local_forage_encoded_blob}function k(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new u(function(a,d){var e=v.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(a){e.result.createObjectStore(c.storeName),a.oldVersion<=1&&e.result.createObjectStore(x)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function l(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),j(a)&&(a=i(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function m(a,b){var c=this,d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;j(d)&&(d=i(d));var e=a(d,c.key,h++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function n(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new u(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,g(f.db)}).then(function(a){return!a&&b instanceof Blob?h(b):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0);var h=g.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}})["catch"](e)});return t(e,c),e}function o(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return t(d,b),d}function p(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return t(c,a),c}function q(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function r(a,b){var c=this,d=new u(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return t(d,b),d}function s(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function t(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var u="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,v=v||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(v){var w,x="local-forage-detect-blob-support",y={_driver:"asyncStorage",_initStorage:k,iterate:m,getItem:l,setItem:n,removeItem:o,clear:p,length:q,key:r,keys:s};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=y:"function"==typeof define&&define.amd?define("asyncStorage",function(){return y}):this.asyncStorage=y}}).call(window)},{promise:76}],79:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":82,promise:76}],80:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":82,promise:76}],81:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){
if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){var k=new g(function(b){if(n===l.DEFINE)a([f],b);else if(n===l.EXPORT)switch(f){case i.INDEXEDDB:b(a("./drivers/indexeddb"));break;case i.LOCALSTORAGE:b(a("./drivers/localstorage"));break;case i.WEBSQL:b(a("./drivers/websql"))}else b(q[f])});k.then(function(a){i._extend(a),c()})}else h[f]?(i._extend(h[f]),c()):(i._driverSet=g.reject(j),d(j))}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":78,"./drivers/localstorage":79,"./drivers/websql":80,promise:76}],82:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=y.BlobBuilder||y.MSBlobBuilder||y.MozBlobBuilder||y.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=k;a instanceof ArrayBuffer?(d=a,e+=m):(d=a.buffer,"[object Int8Array]"===c?e+=o:"[object Uint8Array]"===c?e+=p:"[object Uint8ClampedArray]"===c?e+=q:"[object Int16Array]"===c?e+=r:"[object Uint16Array]"===c?e+=t:"[object Int32Array]"===c?e+=s:"[object Uint32Array]"===c?e+=u:"[object Float32Array]"===c?e+=v:"[object Float64Array]"===c?e+=w:b(new Error("Failed to get type for BinaryArray"))),b(e+g(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=i+a.type+"~"+g(this.result);b(k+n+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(h){console.error("Couldn't convert value into a JSON string: ",a),b(null,h)}}function e(a){if(a.substring(0,l)!==k)return JSON.parse(a);var b,d=a.substring(x),e=a.substring(l,x);if(e===n&&j.test(d)){var g=d.match(j);b=g[1],d=d.substring(g[0].length)}var h=f(d);switch(e){case m:return h;case n:return c([h],{type:b});case o:return new Int8Array(h);case p:return new Uint8Array(h);case q:return new Uint8ClampedArray(h);case r:return new Int16Array(h);case t:return new Uint16Array(h);case s:return new Int32Array(h);case u:return new Uint32Array(h);case v:return new Float32Array(h);case w:return new Float64Array(h);default:throw new Error("Unkown type: "+e)}}function f(a){var b,c,d,e,f,g=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var k=new ArrayBuffer(g),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=h.indexOf(a[b]),d=h.indexOf(a[b+1]),e=h.indexOf(a[b+2]),f=h.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function g(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=h[c[b]>>2],d+=h[(3&c[b])<<4|c[b+1]>>4],d+=h[(15&c[b+1])<<2|c[b+2]>>6],d+=h[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="~~local_forage_type~",j=/^~~local_forage_type~([^~]+)~/,k="__lfsc__:",l=k.length,m="arbf",n="blob",o="si08",p="ui08",q="uic8",r="si16",s="si32",t="ur16",u="ui32",v="fl32",w="fl64",x=l+m.length,y=this,z={serialize:d,deserialize:e,stringToBuffer:f,bufferToString:g};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=z:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return z}):this.localforageSerializer=z}).call(window)},{}],83:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":84,"./lib/inflate":85,"./lib/utils/common":86,"./lib/zlib/constants":89}],84:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":86,"./utils/strings":87,"./zlib/deflate.js":91,"./zlib/messages":96,"./zlib/zstream":98}],85:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":86,"./utils/strings":87,"./zlib/constants":89,"./zlib/gzheader":92,"./zlib/inflate.js":94,"./zlib/messages":96,"./zlib/zstream":98}],86:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],87:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":86}],88:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],89:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],90:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],91:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":86,"./adler32":88,"./crc32":90,"./messages":96,"./trees":97}],92:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],93:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],94:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;
break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":86,"./adler32":88,"./crc32":90,"./inffast":93,"./inftrees":95}],95:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":86}],96:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],97:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":86}],98:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]); | cdnjs/cdnjs | ajax/libs/forerunnerdb/1.3.371/fdb-legacy.min.js | JavaScript | mit | 274,318 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Crc,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
joinMatchData,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self._resolveDynamicQuery(joinMatchData.$query, resultArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatchData, resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = new Path(query.substr(3, query.length - 3)).value(item);
} else {
pathResult = new Path(query).value(item);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
case '2d':
index = new Index2d(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":31}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],9:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - rob@irrelon.com
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":31}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":27}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":27}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":31}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":31}],30:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Handler for Date() objects
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
// Handler for RegExp() objects
this.registerEncoder('$regexp', function (data) {
if (data instanceof RegExp) {
return {
source: data.source,
params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '')
};
}
});
this.registerDecoder('$regexp', function (data) {
var type = typeof data;
if (type === 'object') {
return new RegExp(data.source, data.params);
} else if (type === 'string') {
return new RegExp(data);
}
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],31:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.596',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],33:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload');
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this.publicData().findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
// Check if we have an existing reactor io
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
}
});
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
var self = this;
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (this._view[viewName]) {
return this._view[viewName];
} else {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
self.emit('create', [self._view[viewName], 'view', viewName]);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
| tholu/cdnjs | ajax/libs/forerunnerdb/1.3.596/fdb-core+views.js | JavaScript | mit | 312,713 |
/*!
* Inspire Tree v1.2.4
* https://github.com/helion3/inspire-tree
*
* Copyright 2015 Helion3, and other contributors
* Licensed under MIT. https://github.com/helion3/inspire-tree/blob/master/LICENSE
*/
.itree-menu{background:#ddd;border:1px solid #c4c4c4;border-radius:3px;font-family:sans-serif;list-style:none;margin:0;min-width:150px;padding:0;position:absolute;z-index:10}.itree-menu a{display:block;padding:3px 8px}.itree-menu a:hover{background:#dafaff;color:#a4eaf5}.inspire-tree:focus{outline:none}.inspire-tree ol{list-style:none;margin:0;padding:0}.inspire-tree ol ol{margin-left:20px}.inspire-tree .collapsed>ol,.inspire-tree .hidden{display:none}.inspire-tree a{cursor:default;display:block;height:100%;line-height:25px}.inspire-tree li>.title-wrap{position:relative;z-index:2}.inspire-tree .toggle{height:25px;left:0;position:absolute;top:0;width:25px;z-index:2}.inspire-tree .toggle:before{display:block;left:50%;position:absolute;top:50%;-webkit-transform:translate(-50%,-50%);-ms-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.inspire-tree [type=checkbox]{left:18px;position:absolute;top:4px;vertical-align:middle;width:20px;z-index:2}.inspire-tree .title{overflow:hidden;padding-left:30px;position:relative;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap;z-index:1}.inspire-tree .title:before{left:-6px;position:relative;top:-2px;vertical-align:middle}.inspire-tree .dragging{position:fixed;z-index:5000}.inspire-tree.drop-target{border:1px solid #2dadc5}.inspire-tree .icon:before{background-position:0 0;background-repeat:no-repeat;content:'';display:inline-block;height:14px;width:14px}.inspire-tree .selected>.title-wrap .icon-folder:before{background-image:url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20viewBox%3D%220%200%2032%2032%22%3E%3Cpath%20fill%3D%22%232dadc5%22%20d%3D%22M14%204l4%204h14v22h-32v-26z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E")}.inspire-tree .selected>.title-wrap .icon-file-empty:before{background-image:url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20viewBox%3D%220%200%2032%2032%22%3E%3Cpath%20fill%3D%22%232dadc5%22%20d%3D%22M28.681%207.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378%200-2.5%201.121-2.5%202.5v27c0%201.378%201.122%202.5%202.5%202.5h23c1.378%200%202.5-1.122%202.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543%205.457c0.959%200.959%201.712%201.825%202.268%202.543h-4.811v-4.811c0.718%200.556%201.584%201.309%202.543%202.268zM28%2029.5c0%200.271-0.229%200.5-0.5%200.5h-23c-0.271%200-0.5-0.229-0.5-0.5v-27c0-0.271%200.229-0.5%200.5-0.5%200%200%2015.499-0%2015.5%200v7c0%200.552%200.448%201%201%201h7v19.5z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E")}.inspire-tree .icon-folder:before{background-image:url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20viewBox%3D%220%200%2032%2032%22%3E%3Cpath%20fill%3D%22%23ccc%22%20d%3D%22M14%204l4%204h14v22h-32v-26z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E")}.inspire-tree .icon-caret-down:before,.inspire-tree .icon-caret:before{background-image:url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20viewBox%3D%220%200%2032%2032%22%3E%3Cpath%20fill%3D%22%23222%22%20d%3D%22M6%204l20%2012-20%2012z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E")}.inspire-tree .icon-caret-down:before{-webkit-transform:translate(-50%,-50%) rotate(90deg);-ms-transform:translate(-50%,-50%) rotate(90deg);transform:translate(-50%,-50%) rotate(90deg)}.inspire-tree .icon-file-empty:before{background-image:url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20viewBox%3D%220%200%2032%2032%22%3E%3Cpath%20fill%3D%22%23ccc%22%20d%3D%22M28.681%207.159c-0.694-0.947-1.662-2.053-2.724-3.116s-2.169-2.030-3.116-2.724c-1.612-1.182-2.393-1.319-2.841-1.319h-15.5c-1.378%200-2.5%201.121-2.5%202.5v27c0%201.378%201.122%202.5%202.5%202.5h23c1.378%200%202.5-1.122%202.5-2.5v-19.5c0-0.448-0.137-1.23-1.319-2.841zM24.543%205.457c0.959%200.959%201.712%201.825%202.268%202.543h-4.811v-4.811c0.718%200.556%201.584%201.309%202.543%202.268zM28%2029.5c0%200.271-0.229%200.5-0.5%200.5h-23c-0.271%200-0.5-0.229-0.5-0.5v-27c0-0.271%200.229-0.5%200.5-0.5%200%200%2015.499-0%2015.5%200v7c0%200.552%200.448%201%201%201h7v19.5z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E")}.inspire-tree .loading>.title-wrap .title:before{background:url(863c5a2796b088dea28a1f75a0973372.gif) 0 0 no-repeat;content:'';height:14px;width:14px}.inspire-tree>ol{position:relative}.inspire-tree .wholerow{height:25px;left:0;position:absolute;-webkit-transform:translateY(-100%);-ms-transform:translateY(-100%);transform:translateY(-100%);width:100%;z-index:1}.inspire-tree .focused:not(.selected)>.wholerow,.inspire-tree .title-wrap:hover+.wholerow{background:#dafaff}.inspire-tree .selected>.title-wrap:hover+.wholerow,.inspire-tree .selected>.wholerow{background:#a4eaf5} | sreym/cdnjs | ajax/libs/inspire-tree/1.2.4/inspire-tree.css | CSS | mit | 5,680 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/OldView":27,"../lib/OldView.Bind":26,"../lib/Overview":30,"../lib/Persist":32,"../lib/View":38}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Shared":37}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
// Convert the index object to an array of key val objects
this.keys(this.extractKeys(index));
}
return this.$super.call(this, index);
});
BinaryTree.prototype.extractKeys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._keys[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
BinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path(),
indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = pathSolver.parseArr(this._index, {
verbose: true
});
queryArr = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":31,"./Shared":37}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.emit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; }
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
return new Path(query.substr(3, query.length - 3)).value(item)[0];
}
return new Path(query).value(item)[0];
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":29,"./Path":31,"./ReactorIO":35,"./Shared":37}],5:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":4,"./Shared":37}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
callback();
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":15,"./Overload":29,"./Shared":37}],7:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":29,"./Shared":37}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
if (callback) { callback(false, true); }
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance.
* @func document
* @memberof Db
* @param {String} documentName The name of the document to create.
* @returns {*}
*/
Db.prototype.document = function (documentName) {
if (documentName) {
// Handle being passed an instance
if (documentName instanceof FdbDocument) {
if (documentName.state() !== 'droppped') {
return documentName;
} else {
documentName = documentName.name();
}
}
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":4,"./Shared":37}],10:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener );
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37,"./View":38}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
}
seriesData.push({
name: seriesName,
data: seriesValues
});
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () { self._changeListener.apply(self, arguments); });
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () { self.drop.apply(self); });
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if(typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy
);
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) { callback(false, true); }
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":29,"./Shared":37}],12:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":31,"./Shared":37}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":31,"./Shared":37}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":37}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":28,"./Shared":37}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":29,"./Serialiser":36}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":29}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) {
return true;
} else if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
}
return -1;
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":29}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":37}],27:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":4,"./CollectionGroup":5,"./Shared":37}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":31,"./Shared":37}],29:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],30:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
delete this._name;
this.emit('drop', this);
if (callback) { callback(false, true); }
}
return true;
};
Db.prototype.overview = function (overviewName) {
if (overviewName) {
// Handle being passed an instance
if (overviewName instanceof Overview) {
return overviewName;
}
this._overview = this._overview || {};
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":4,"./Document":9,"./Shared":37}],31:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":37}],32:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
callback(false, val, {});
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) {
callback(err, data, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) {
callback('Cannot save a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot save a collection with no assigned name!');
}
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) {
callback(err, tableStats, metaStats);
}
});
} else {
if (callback) {
callback(err);
}
}
});
} else {
if (callback) {
callback('Cannot load a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot load a collection with no assigned name!');
}
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Db.prototype.load = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
obj[index].load(loadCallback);
}
}
};
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Db.prototype.save = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
obj[index].save(saveCallback);
}
}
};
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":33,"./PersistCrypto":34,"./Shared":37,"async":39,"localforage":81}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":37,"pako":83}],34:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":37,"crypto-js":48}],35:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":37}],36:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Register our handlers
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],37:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.403',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":29}],38:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (!this._view[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37}],39:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":74}],40:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],41:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":42}],42:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":42}],44:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":42}],45:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":42,"./hmac":47,"./sha1":66}],46:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":41,"./core":42}],47:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":42}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":40,"./cipher-core":41,"./core":42,"./enc-base64":43,"./enc-utf16":44,"./evpkdf":45,"./format-hex":46,"./hmac":47,"./lib-typedarrays":49,"./md5":50,"./mode-cfb":51,"./mode-ctr":53,"./mode-ctr-gladman":52,"./mode-ecb":54,"./mode-ofb":55,"./pad-ansix923":56,"./pad-iso10126":57,"./pad-iso97971":58,"./pad-nopadding":59,"./pad-zeropadding":60,"./pbkdf2":61,"./rabbit":63,"./rabbit-legacy":62,"./rc4":64,"./ripemd160":65,"./sha1":66,"./sha224":67,"./sha256":68,"./sha3":69,"./sha384":70,"./sha512":71,"./tripledes":72,"./x64-core":73}],49:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":42}],50:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":42}],51:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":41,"./core":42}],52:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby jhruby.web@gmail.com
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":41,"./core":42}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":41,"./core":42}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":41,"./core":42}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":41,"./core":42}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":41,"./core":42}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":41,"./core":42}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":41,"./core":42}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":41,"./core":42}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":41,"./core":42}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":42,"./hmac":47,"./sha1":66}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],65:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":42}],66:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":42}],67:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":42,"./sha256":68}],68:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":42}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":42,"./x64-core":73}],70:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":42,"./sha512":71,"./x64-core":73}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":42,"./x64-core":73}],72:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],73:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":42}],74:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],75:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
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')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(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 (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":77}],76:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
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.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":75,"asap":77}],77:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":74}],78:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB ||
this.mozIndexedDB || this.OIndexedDB ||
this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = window.BlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({status: xhr.status, response: xhr.response});
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function(resolve, reject) {
var blob = _createBlob([''], {type: 'image/png'});
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function() {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE],
'readwrite');
var getBlobReq = blobTxn.objectStore(
DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function(e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function(res) {
resolve(!!(res && res.type === 'image/png'));
}, function() {
resolve(false);
}).then(function() {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function() {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function(value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function(e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type});
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function(e) {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// added when support for blob shims was added
openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void(0)) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
var dbInfo;
self.ready().then(function() {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function(blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function(value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function() {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function() {
resolve();
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = asyncStorage;
} else if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":76}],79:[function(_dereq_,module,exports){
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
self._dbInfo = dbInfo;
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
return serializerPromise.then(function(lib) {
serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), i + 1);
if (value !== void(0)) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function(keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function(resolve, reject) {
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.EXPORT) {
module.exports = localStorageWrapper;
} else if (moduleType === ModuleType.DEFINE) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"./../utils/serializer":82,"promise":76}],80:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof(options[i]) !== 'string' ?
options[i].toString() : options[i];
}
}
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
var dbInfoPromise = new Promise(function(resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version),
dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function() {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function(t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName +
' (id INTEGER PRIMARY KEY, key unique, value)', [],
function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
});
});
return serializerPromise.then(function(lib) {
serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName +
' WHERE key = ? LIMIT 1', [key],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = serializer.deserialize(result);
}
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [],
function(t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void(0)) {
resolve(result);
return;
}
}
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('INSERT OR REPLACE INTO ' +
dbInfo.storeName +
' (key, value) VALUES (?, ?)',
[key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName +
' WHERE key = ?', [key],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' +
dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName +
' WHERE id = ? LIMIT 1', [n + 1],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).key : null;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [],
function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.DEFINE) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"./../utils/serializer":82,"promise":76}],81:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports &&
typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [
DriverType.INDEXEDDB,
DriverType.WEBSQL,
DriverType.LOCALSTORAGE
];
var LibraryMethods = [
'clear',
'getItem',
'iterate',
'key',
'keys',
'length',
'removeItem',
'setItem'
];
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function(self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB ||
self.mozIndexedDB || self.OIndexedDB ||
self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function() {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator &&
self.navigator.userAgent &&
/Safari/.test(self.navigator.userAgent) &&
!/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB &&
typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function() {
try {
return (self.localStorage &&
('setItem' in self.localStorage) &&
(self.localStorage.setItem));
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) &&
DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof(options) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " +
'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof(options) === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function(driverObject, callback,
errorCallback) {
var defineDriver = new Promise(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
'Custom driver not compliant; see ' +
'https://mozilla.github.io/localForage/#definedriver'
);
var namingError = new Error(
'Custom driver name already in use: ' + driverObject._driver
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod ||
!driverObject[customDriverMethod] ||
typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function(supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
})['catch'](reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
var driverPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
switch (driverName) {
case self.INDEXEDDB:
resolve(_dereq_('./drivers/indexeddb'));
break;
case self.LOCALSTORAGE:
resolve(_dereq_('./drivers/localstorage'));
break;
case self.WEBSQL:
resolve(_dereq_('./drivers/websql'));
break;
}
} else {
resolve(globalObject[driverName]);
}
});
driverPromise.then(function(driver) {
self._extend(driver);
resolve();
});
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
resolve();
} else {
self._driverSet = Promise.reject(error);
reject(error);
}
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":78,"./drivers/localstorage":79,"./drivers/websql":80,"promise":76}],82:[function(_dereq_,module,exports){
(function() {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder ||
globalObject.MSBlobBuilder ||
globalObject.MozBlobBuilder ||
globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' +
bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ",
value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], {type: blobType});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i+=4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i+1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i+2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i+3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if ((bytes.length % 3) === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = localforageSerializer;
} else if (typeof define === 'function' && define.amd) {
define('localforageSerializer', function() {
return localforageSerializer;
});
} else {
this.localforageSerializer = localforageSerializer;
}
}).call(window);
},{}],83:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":84,"./lib/inflate":85,"./lib/utils/common":86,"./lib/zlib/constants":89}],84:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":86,"./utils/strings":87,"./zlib/deflate.js":91,"./zlib/messages":96,"./zlib/zstream":98}],85:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":86,"./utils/strings":87,"./zlib/constants":89,"./zlib/gzheader":92,"./zlib/inflate.js":94,"./zlib/messages":96,"./zlib/zstream":98}],86:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],87:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":86}],88:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],89:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],90:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],91:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":86,"./adler32":88,"./crc32":90,"./messages":96,"./trees":97}],92:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],93:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],94:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":86,"./adler32":88,"./crc32":90,"./inffast":93,"./inftrees":95}],95:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":86}],96:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],97:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":86}],98:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
| nolsherry/cdnjs | ajax/libs/forerunnerdb/1.3.403/fdb-legacy.js | JavaScript | mit | 909,968 |
# encoding: utf-8
module Mongoid #:nodoc:
class Identity #:nodoc:
attr_reader :document
# Create the identity for the document. The id will be set in either in
# the form of a Mongo object id or a composite key set up by defining
# a key on the document. The _type will be set to the document's class
# name.
#
# @example Create the id and set the type.
# identity.create
def create
identify.tap { type }
end
# Create the new identity generator - this will be expanded in the future
# to support pk generators.
#
# @example
# Identity.new(document)
#
# @param [ Document ] document The document to generate an id for.
#
# @return [ Identity ] The new identity object.
def initialize(document)
@document = document
end
private
# Return the proper id for the document. Will be an object id or its string
# representation depending on the configuration.
#
# @example Generate the id.
# identity.generate_id
#
# @return [ Object ] The bson object id or its string equivalent.
def generate_id
id = BSON::ObjectId.new
document.using_object_ids? ? id : id.to_s
end
# Sets the id on the document. Will either set a newly generated id or
# build the composite key.
#
# @example Set the id.
# identity.identify
def identify
document.id = compose.join(" ").identify if document.primary_key
document.id = generate_id if document.id.blank?
document.id
end
# Set the _type field on the document if the document is hereditary or in a
# polymorphic relation.
#
# @example Set the type.
# identity.type
def type
document._type = document.class.name if typed?
end
# Generates the array of keys to build the id.
#
# @example Build the array for the keys.
# identity.compose.
#
# @return [ Array<Object> ] The array of keys.
def compose
kf = document.key_formatter
document.primary_key.collect do |key|
val = document.attributes[key.to_s]
val && kf ? kf.call(val) : val
end.compact
end
# Determines if the document stores the type information. This is if it is
# in a hierarchy, has subclasses, or is in a polymorphic relation.
#
# @example Check if the document is typed.
# identity.typed?
#
# @return [ true, false ] True if typed, false if not.
def typed?
document.hereditary? ||
document.class.descendants.any? ||
document.polymorphic?
end
end
end
| FestivalBobcats/mongoid | lib/mongoid/identity.rb | Ruby | mit | 2,611 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.